Be careful of deferred execution

Take the following code, if you have ReSharper installed you’ll be warned that there is possible multiple enumeration of your IEnumerable, this means that  Select will be repeated twice for everything in the array.image

ToArray()

One solution is to Enumerate one and immediately after the select by calling .ToArrayimage

 

 

Guava / Java

It’s not just C# that you need to be careful with, take the google java library Guava

image We don’t get the same nice warning in IntelliJ* yet the solution in this case is much the same.

image

 

*IntelliJ

If you’re from a MS background like me and doing any Java, then do yourself a favour and use IntelliJ, it’s much easier to use.

Efficiency Yield

Talking to an ex colleague of mine this evening about some use cases for yield, it’s quite a handy little keyword, i often use it for splitting a large collection into smaller ones (Chunk).

image

Efficiency

I was presented with another use for yield.

Take a third party API that takes an IEnumerable of objects that are expensive to create,

image

 

 

 


we can see that there is an early imageexit strategy so we may not need all items in the enumeration.

 

 

 

 


Now lets say we have 3 implementations of this interfaceimage

trivial i know, but assume we don’t know if they return null or not at compile time.

 

 

Now here’s a nice way of passing all of the above to a third party API and only incur the construction hit as and if when they get enumerated.

image

Using the trivial logic outlined here, ExpensiveFactoryC will never get constructed.