Sunday, August 16, 2009

Enumerating sequential containers in C#

Here I’ve posted my performance comparison when it’s simply needed to enumerate a sequential array. I calculated control sum on all elements. In the first table array element is value-type, in the second – reference-type. I used very long arrays, however I believe it makes sense when you really need to speed up your code and array length is greater than 1000 elements.






int[]List<int>Collection<int>
for0,1050,160,297
foreach0,1720,340,551
IEnumerator11,5620,8830,937
Linq0,7070,9021,219







Int[]List<Int>Collection<Int>
for0,2380,2970,395
foreach0,230,4020,785
IEnumerator2,7340,860,875
Linq0,751,2581,543

avoid IEnumerator at all IEnumerator gave the unexpected result; it will be the bad idea to use it in a performance critical code and to use it all in comparison with another simpler syntaxes.
Collection or its descendants are not intended to improve performance I knew that before the test and here I’ve asserted it. Better to use it on upper abstraction level to bind interfaces and not in local or class scopes at all.
foreach slowed down performance myth is busted I supposed that foreach with its type casting at every turn will slow down performance. However it’s not. Moreover if iEnd index local variable is not used and at every turn array.Length or list.Count dereference occurs, for cycle results will be worse than the posted here. So in most real cases I can’t mark out for or foreach cycle. They both are good.
array[] is a little bit faster than List<>
Linq - I expected better results However I can’t give the conclusion about Linq here. Additional research is required.