LINQ versus nested loop

In Im code, a generic template is supported, such as the following, a nested loop with if to find specific elements.

foreach (Storage storage in mStorage.Values) foreach (OrderStorage oStorage in storage.OrderStorage) if (oStorage.OrderStorageId == orderStorageId) 

I was thinking of changing this in LINQ:

  foreach (OrderStorage oStorage in (from storage in mStorage.Values from oStorage in storage.OrderStorage where oStorage.OrderStorageId == orderStorageId select oStorage)) 

But it does not seem so attractive, because it is less transparent, what is happening here, more objects can be created in terms of costs both in terms of memory and from the processor. Will more objects be created or will the C # compiler emit code similar to a nested loop with if inside?

+4
source share
1 answer

Will more objects be created or will the C # compiler emit code similar to a nested loop with if inside?

Other objects; each LINQ operation ( SelectMany , Where , Select , etc.) will lead to the creation of a new place owner object that represents the pending IEnumerable<T> request for this operation, and then, when it finally repeats, each of them will result to an instance of an enumerator along with context, etc. In addition, there is a context with a captured variable for raised orderStorageId , etc.

Note that regular foreach will also lead to an instance of the enumerator, but foreach has the advantage that it can also use numbered enumerations, which means that for things like List<T> , the struct is actually used, not the class enumerator . And, of course, using a local variable ( orderStorageId ) directly (and not by an anonymous method) means that it does not need to be raised to a state / context object.

So, the original foreach more direct and efficient. An interesting question: is the difference important? Sometimes it is, sometimes it is not.

+14
source

Source: https://habr.com/ru/post/1496129/


All Articles