<p>I have an application that uses NHibernate as its ORM and sometimes it experiences performance issues due to how the data is being accessed by it. What kind of things can be done to improve the performance of NHibernate? (Please limit to one recommendation per answer)</p>

[{'answer_id': 67267, 'author': 'Mike Monette', 'author_id': 6166, 'author_profile': 'https://Stackoverflow.com/users/6166', 'pm_score': 2, 'selected': False, 'text': "<p>Without any specifics about the kinds of performance issues you're seeing, I can only offer a generalization:  In my experience, most database query performance issues arise from lack of proper indices.  So my suggestion for a first action would be to check your query plans for non-indexed queries.</p>\n"}, {'answer_id': 67479, 'author': 'Chuck', 'author_id': 9714, 'author_profile': 'https://Stackoverflow.com/users/9714', 'pm_score': 7, 'selected': True, 'text': "<p>The first and most dramatic performance problem that you can run into with NHibernate is if you are creating a new session factory for every session you create.  Only one session factory instance should be created for each application execution and all sessions should be created by that factory.</p>\n\n<p>Along those lines, you should continue using the same session as long as it makes sense.  This will vary by application, but for most web applications, a single session per request is recommended.  If you throw away your session frequently, you aren't gaining the benefits of its cache.  Intelligently using the session cache can change a routine with a linear (or worse) number of queries to a constant number without much work.  </p>\n\n<p>Equally important is that you want to make sure that you are lazy loading your object references.  If you are not, entire object graphs could be loaded for even the most simple queries.  There are only certain reasons not to do this, but it is always better to start with lazy loading and switch back as needed.</p>\n\n<p>That brings us to eager fetching, the opposite of lazy loading.  While traversing object hierarchies or looping through collections, it can be easy to lose track of how many queries you are making and you end up with an exponential number of queries.  Eager fetching can be done on a per query basis with a FETCH JOIN.  In rare circumstances, such as if there is a particular pair of tables you always fetch join, consider turning off lazy loading for that relationship.</p>\n\n<p>As always, SQL Profiler is a great way to find queries that are running slow or being made repeatedly.  At my last job we had a development feature that counted queries per page request as well.  A high number of queries for a routine is the most obvious indicator that your routine is not working well with NHibernate.  If the number of queries per routine or request looks good, you are probably down to database tuning; making sure you have enough memory to store execution plans and data in the cache, correctly indexing your data, etc.</p>\n\n<p>One tricky little problem we ran into was with SetParameterList().  The function allows you to easily pass a list of parameters to a query.  NHibernate implemented this by creating one parameter for each item passed in.  This results in a different query plan for every number of parameters.  Our execution plans were almost always getting released from the cache.  Also, numerous parameters can significantly slow down a query.  We did a custom hack of NHibernate to send the items as a delimited list in a single parameter.  The list  was separated in SQL Server by a table value function that our hack automatically inserted into the IN clause of the query.  There could be other land mines like this depending on your application.  SQL Profiler is the best way to find them.</p>\n"}, {'answer_id': 98514, 'author': 'Eric Lathrop', 'author_id': 18392, 'author_profile': 'https://Stackoverflow.com/users/18392', 'pm_score': 2, 'selected': False, 'text': '<p>NHibernate generates pretty fast SQL right out of the box.\nI\'ve been using it for a year, and have yet to have to write bare SQL with it.\nAll of my performance problems have been from <a href="http://www.codinghorror.com/blog/archives/001152.html" rel="nofollow noreferrer">Normalization</a> and lack of indexes.</p>\n\n<p>The easiest fix is to examine the execution plans of your queries and create proper indexes, especially on your foreign key columns. If you are using Microsoft SQL Server, the "Database Engine Tuning Advisor" helps out a lot with this.</p>\n'}, {'answer_id': 106178, 'author': 'lotsoffreetime', 'author_id': 18248, 'author_profile': 'https://Stackoverflow.com/users/18248', 'pm_score': 1, 'selected': False, 'text': '<p>If you\'re not already using lazy loading (appropriately), start. Fetching collections when you don\'t need them is a waste of everything.</p>\n\n<p><a href="http://nhibernate.info/doc/nhibernate-reference/performance.html" rel="nofollow noreferrer">Chapter Improving performance</a> describes this and other ways to improve performance.</p>\n'}, {'answer_id': 119932, 'author': 'Richard', 'author_id': 20038, 'author_profile': 'https://Stackoverflow.com/users/20038', 'pm_score': 1, 'selected': False, 'text': '<p>Profiling is the first step - even simple timed unit tests - to find out where the greatest gains can be made</p>\n\n<p>For collections consider setting the batch size to reduce the number of select statements issued - see section <a href="http://nhibernate.info/doc/nhibernate-reference/performance.html" rel="nofollow noreferrer">Improving performance</a> for details</p>\n'}, {'answer_id': 123996, 'author': 'Hace', 'author_id': 18703, 'author_profile': 'https://Stackoverflow.com/users/18703', 'pm_score': 1, 'selected': False, 'text': '<p>I am only allowed to limit my answer to one option? In that case I would select that you implement the second-level cache mechanism of NHibernate. </p>\n\n<p>This way, for each object in your mapping file you are able to define the cache-strategy. The secondlevel cache will keep already retrieved objects in memory and therefore not make another roundtrip to the database. This is a huge performance booster.</p>\n\n<p>Your goal is to define the objects that are constantly accessed by your application. Among those will be general settings and the like.</p>\n\n<p>There is plenty of information to be found for nhibernate second level cache and how to implement it.</p>\n\n<p>Good luck :)</p>\n'}, {'answer_id': 187643, 'author': 'Watson', 'author_id': 25807, 'author_profile': 'https://Stackoverflow.com/users/25807', 'pm_score': 1, 'selected': False, 'text': '<p>Caching, Caching, Caching -- Are you using your first level caching correctly [closing sessions prematurely, or using StatelessSession to bypass first level caching]?  Do you need to set up a simple second level cache for values that  change infrequently?  Can you cache query result sets to speed up queries that change infrequently?</p>\n\n<p>[Also configuration -- can you set items as immutable? Can you restructure queries to bring back only the information you need and transform them into the original entity? Will Batman be able to stop the Riddler before he gets to the dam? ... oh, sorry got carried away.]</p>\n'}, {'answer_id': 238788, 'author': 'David P', 'author_id': 13145, 'author_profile': 'https://Stackoverflow.com/users/13145', 'pm_score': 5, 'selected': False, 'text': '<p>NHibernate\'s SessionFactory is an expensive operation so a good strategy is to creates a Singleton which ensures that there is only ONE instance of SessionFactory in memory:</p>\n\n<pre><code>   public class NHibernateSessionManager\n    {\n        private readonly ISessionFactory _sessionFactory;\n\n        public static readonly NHibernateSessionManager Instance = new NHibernateSessionManager();\n\n        private NHibernateSessionManager()\n        {\n            if (_sessionFactory == null)\n            {\n                System.Diagnostics.Debug.WriteLine("Factory was null - creating one");\n                _sessionFactory = (new Configuration().Configure().BuildSessionFactory());\n            }\n        }\n\n        public ISession GetSession()\n        {\n            return _sessionFactory.OpenSession();\n        }\n\n        public void Initialize()\n        {\n            ISession disposeMe = Instance.GetSession();\n        }\n    }\n</code></pre>\n\n<p>Then in your Global.Asax Application_Startup, you can initialize it:</p>\n\n<pre><code>protected void Application_Start()\n{\n    NHibernateSessionManager.Instance.Initialize();\n}\n</code></pre>\n'}, {'answer_id': 335235, 'author': 'Ray', 'author_id': 4872, 'author_profile': 'https://Stackoverflow.com/users/4872', 'pm_score': 4, 'selected': False, 'text': '<p>Avoid and/or minimize the <a href="http://ayende.com/Blog/archive/2008/12/01/solving-the-select-n1-problem.aspx" rel="noreferrer">Select N + 1 problem</a> by recognizing when to switch from lazy loading to eager fetching for slow performing queries.</p>\n'}, {'answer_id': 504433, 'author': 'MatthieuGD', 'author_id': 3109, 'author_profile': 'https://Stackoverflow.com/users/3109', 'pm_score': 4, 'selected': False, 'text': '<p>No a recommendation but a tool to help you : NH Prof ( <a href="http://nhprof.com/" rel="noreferrer">http://nhprof.com/</a> ) seems to be promising, it can evaluate your use of the ORM framework. It can be a good starting point for your tunning of NHibernate.</p>\n'}, {'answer_id': 1268950, 'author': 'Axl', 'author_id': 16605, 'author_profile': 'https://Stackoverflow.com/users/16605', 'pm_score': 0, 'selected': False, 'text': '<p>What lotsoffreetime said.</p>\n\n<p>Read Chapter 19 of the documentation, "Improving Performance".<br>\nNHibernate: <a href="http://nhibernate.info/doc/nhibernate-reference/performance.html" rel="nofollow noreferrer">http://nhibernate.info/doc/nhibernate-reference/performance.html</a><br>\nHibernate: <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html" rel="nofollow noreferrer">http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html</a></p>\n\n<p>Use SQL Profiler (or equivalent for the database you\'re using) to locate long-running queries. Optimize those queries with appropriate indexes. </p>\n\n<p>For database calls used on nearly every single page of an application, use CreateMultiQuery to return multiple resultsets from a single database query. </p>\n\n<p>And of course, cache. The OutputCache directive for pages/controls. NHibernate caching for data.</p>\n'}, {'answer_id': 8042258, 'author': 'gnome26', 'author_id': 1034479, 'author_profile': 'https://Stackoverflow.com/users/1034479', 'pm_score': 2, 'selected': False, 'text': '<p>"One recommendation per answer" only? Then I would go for this one:</p>\n\n<p>Avoid join duplicates (AKA cartesian products) due to joins along two or more parallel to-many associations; use Exists-subqueries, MultiQueries or FetchMode "subselect" instead.</p>\n\n<p>Taken from: <a href="http://arnosoftwaredev.blogspot.com/2011/01/hibernate-performance-tips.html" rel="nofollow">Hibernate Performance Tuning Tips </a></p>\n'}]
['https://Stackoverflow.com/questions/67103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4872/']