Tuesday, October 4, 2011

what is an n+1 problem?

I often heard talk of n+1 problems when I worked at Headspring. Today was the day I finally asked someone (Rafael Torres) what an n+1 problem is.
  1. If one has an object and the object has a collection of children...
  2. And, if one queries the number of children...
  3. And if one then runs a while (myCounter < numberOfChildren) loop, querying a child object for each of the passes through the loop...
  4. One will have n number of queries for n number of children...
  5. +1 query for the query to get the count (or is it the query to get the object to begin with? –I’m fuzzy on this.)
This is a lot of queries. It is going to get "heavy" in some situations. This is the way NHibernate works unless one uses Eager Fetching to get children with a parent upon pulling a parent from a database.

No comments:

Post a Comment