After posting my last blog entry regarding LINQ, Jonas Högström pinged me on Skype. He asked me, why I had used Count<string>() instead of Count(). As IEnumerable<> already was only carrying string objects, there was no need to do that. I agreed, but said that I fell into a trap with Intellisense. Visual Studio makes it so easy to enter code that you sometimes make your code too verbose. However, I waondered if there was a performance penalty to be paid as I definitely was calling a method that seems to be more complicated. So I used my good old friend the ildasm and asked him what he thought.
I wrote a short test case which called Count() and then Count<string>(). This is the reply he gave me:
int32 [System.Core]System.Linq.Enumerable::Count(class [mscorlib]System.Collections.Generic.IEnumerable`1) call void [mscorlib]System.Console::WriteLine(int32) nop ldloc.1 call int32 [System.Core]System.Linq.Enumerable::Count(class [mscorlib]System.Collections.Generic.IEnumerable`1) call void [mscorlib]System.Console::WriteLine(int32) nop
Thus, we can see that both calls to Count<string>() and to Count() result in the very same intermediate assembly code. So, the compiler makes the choice for us. There is absolutely no performance penalty involved as the same method is being called internally.

No comments
Comments feed for this article
Trackback link
http://www.flickdotnet.de/index.php/2008/01/ienumerable-the-difference-between-count-and-count/trackback/