2

I am aware of this answer that explains what setting lazy="extra" does.

My question is, is there any costs associated with using lazy="extra"? Why wouldn't we just set lazy="extra" to every instance where we would otherwise set it to "true"? It seems it is same as "true" but better?

Community
  • 1
  • 1
syclee
  • 697
  • 7
  • 18

1 Answers1

4

The only thing I can think of is that if a collection is mostly used as data source or for iterating on a loop it would be better to get the full collection first time you access ANY property (even Count).

Otherwise you might end up executing more queries than necessary.

For example

bool found = false;
int pos = 0;
while (!found && pos < Collection.Count)
{
    if (MyFunction(Collection[pos]))
    {
         found = true;
    }
    pos++;
}
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • Yes that makes sense, so when you have a collection that will definitely be used after a .Count call, then you would set lazy="true" to save the count sql query before using it. I still think the cost of doing this is much less than the potential cost by not doing this. So isn't the default thing to do is to set lazy="extra" always, and only in cases you know you will need the collection anyway, set lazy="true" for those circumstances? – syclee Mar 22 '12 at 01:02
  • I'd say it will depende on the size of the collection. If it's big I think it's worth to use lazy=extra since the cost of the count operation is insignificant in comparison to build the whole collection. Haven't found NH reference, but Hibernate docs says that every item access on the loop would generate a query (items are loaded as required) – Claudio Redi Mar 22 '12 at 12:37