How much does it cost to create NHibernate ISession

by toni 9. February 2012 19:25

Creating NHibernate’s ISession is cheap. At least that’s what everyone says. I wanted to know exactly how cheap it is. For this test I’m using NHibernate v3.2. All times are milliseconds unless otherwise noted. Tests were run on a desktop machine (Core i7). All tests were run in isolation meaning I started the test again by running the compiled console application and giving it number of repeats as a command line parameter.

Update 12.2.2011 Second part is available.

Results

 

Repeats Create (ms) Create and dispose (ms)
1 19 32
100 23 36
125 24 38
250 30 43
500 39 55
1000 68 82
2000 120 127
4000 222 216
8000 417 402

These results look funny. There is no way creating 100 sessions takes almost as much time as creating single session. It makes no sense. Time to investigate what’s going on.

Creating ISession

Code used to measure how long session creation took

var stopWatch = Stopwatch.StartNew();
ISession tempSession;
for (int i = 0; i < max; i++)
{
    tempSession = SessionFactory.OpenSession();
}
stopWatch.Stop();

Creating and disposing ISession

Code used to measure how long session creation and dispose took.

var stopWatch = Stopwatch.StartNew();
ISession tempSession;
for (int i = 0; i < max; i++)
{
    tempSession = SessionFactory.OpenSession();
    tempSession.Dispose();
}
stopWatch.Stop();

Cost of creating the very first session

As I looked the results I was wondering why creating 100 sessions doesn’t take even twice as long as creating single session. It looks like the first session creation is the expensive one. So I ran the following test.

for (int j = 0; j < 10; j++)
{
    var stopWatch = Stopwatch.StartNew();
    ISession tempSession;
    for (int i = 0; i < max; i++)
    {
        tempSession = SessionFactory.OpenSession();
        tempSession.Dispose();
    }
    stopWatch.Stop();

    Console.WriteLine("{0} sessions created in {1} ms",
        max, stopWatch.ElapsedMilliseconds);                
}

The output in my console window looked like this

10 sessions created in 33 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms
10 sessions created in 0 ms

Now it makes sense. Creating the very first session takes time. All the others are really fast. As long as you are not recreating the ISessionFactory (which you shouldn’t do anyway) you only pay the price in the very first session creation.

Pingbacks and trackbacks (1)+

Comments are closed