A place to discuss Development techniques, .NET, XNA, NHibernate or anything else that tickles your fancy

Tuesday, July 7, 2009

NHibernate Tip #1 - Lazy Loading

I wanted to jot down all of the NHibernate tips and tricks that I've learned over the last year of using this thing in production, so this is everything I can remember up to current. Every day until I run out of things I've encountered, I'll be publishing another tip.

Lazy Load Everything - Unless working in a remoting type of environment where you're not guaranteed a session while working with the objects, it's best to let this default to true for all of your entities. I've been burned by this hard, there's a fundamental misunderstanding that I had when starting to pre-optimize (also a bad idea). It went something like this: If I don't lazy load an entity, my application will perform better, because it will have eagerly fetched the data that I will use 80% of the time.

The problem is that lazy loading does not eagerly fetch anything for you. All it does, is execute the same SQL statement to get the object, that it was going to when you eventually attempted to access it, except it's going to do that 100% of the time now. Setting this option to false does *not* improve performance in any way, in fact, in every case, it will actually degrade performance. This is a feature, that as far as I can tell, should only be changed to false when you've got an object graph that loses scope from the session (such as in remoting).

What most people are looking for when they set this to false on a mapping, is the "fetch=join" attribute. This will include the associated entity in the same SQL statement used to get the originating entity. I'll probably make another post about the join fetch, all I can say for now is to use that sparingly. It can improve performance, but should be set at a more granular level (A Criteria or HQL query), as opposed to the entirety of the application.

0 comments:

Post a Comment