Why I use the NHibernate Profiler for optimal ORM performance

In this post I want to show how the NHibernate Profiler can help you avoid ORM performance issues as discussed in the post ‘ORMs don’t kill databases. Developers do.‘.

While it’s not open source it’s definitely worth the investment if you use NHibernate because it can give you alerts about any potential issues and information about how to resolve them.

Something that a profiling tool like SQL Profiler just can’t do.

For example by running the code below to insert 200 apples and then retrieve them from the database

Note: this code is meant to be written like this to generate alerts

[Test]
public void NHibernate_Profiler_Demo()
{
    using (IStatelessSession session = FruitDatabase.SessionFactory.OpenStatelessSession())
    {
        using (ITransaction txn = session.BeginTransaction(IsolationLevel.ReadCommitted))
        {
            for (int i = 0; i < 200; i++)
            {
                var apple = new Fruit() { Name = "Apple" };
                session.Insert(apple);
            }
            txn.Commit();
        }                   
    }
    using (IStatelessSession session = FruitDatabase.SessionFactory.OpenStatelessSession())
    {                              
            var results = session.Query<Fruit>().ToList();                                           
    }
}

the NHibernate Profiler gives a warning about the ‘large number of individual writes’ and a suggestion about having ‘too many database calls per session’.

As you can see in the screenshot there are links to read more which takes you to a takes you to a page with helpful tips to resolve issue and a link to ignore the alert (not recommended!).

This isn’t the only alert that is raised when writing, so you should repeat the cycle of test and fix until no further alerts are raised, the queries/execution plan and/or code have been optimized e.g. changing how/where identifiers are created.

NHibernate Profiler alerts about reads

In addition to detecting problems when writing data the NHibernate profiler can give you tips when reading data.

For the example in this post there are alerts for an unbounded result set and an implicit transaction. Again these probably won’t be the only alerts raised.

Additional features in the NHibernate Profiler include being able to see the result of the query and the execution plan, the ability to compare sessions and a general overview of how an application is interacting with a database.

Check out this live HTML Demo to give it a test run.

There are also versions available for other ORMs like Entity Framework, unfortunately you’ll have to buy a separate licence for each one.

So while you could write your own solution to log and analyse interactions between your app and the database, the NHibernate Profiler will save you so much time because it can do the investigative work for you.

Comments