Memory usage in a foreach loop C#
I have a foreach loop
var axsEntities = GetAxsEntitiesForInvoi开发者_JS百科cing(adapter)
.GroupBy(x => x.AccountUsingAccountIdToAccountId);
foreach(var gbAccount in axsEntities)
{
int i = gbAccount.count();
}
Now when i run this without the loop it runs fine, but with the loop it uses way too much memory, 3 gigabytes in this case. What could be the reason for this?
Thanks
Without the loop, nothing is really happening.
axsEntities
is just an IEnumerable with deferred execution.
Creating it is always cheap. Only when Iterating over it (the foreach
) things are being fetched and computed.
So you just might have very many elements, or .count()
uses a lot of memory.
We'd have to see what type axsEntitie is to be sure, but I'm guessing it is a IQueryable? If so, without the for loop you aren't actually doing anything on that set. With the for loop you're actually iterating the result set.
The first expression is probably lazy evaluated. Try a simple
var test = axsEntities.ToList();
to see if that also uses a lot of memory.
The problem likely is NOT the forreach loop, but the GroupBy logic that is delay executed in the loop.
Unless the GetAxyEntitiesForInvoicing method is IQueryable and does not return all entities, the grouping has to happen in memory.
What about gbAccount.count();
inside a foreach loop? This might not be a good idea. I would first check to see if this is responsible for using the precious memory. My advice is that you could come up with a more specialized query e.g. GetAccountsCountForGroupedAxsEntitiesForInvoicingByAccountUsingAccountIdToAccountIdWithSauce
, this sounds like a really nice name to me.
Peace
精彩评论