|
|
|
|
|
by MichaelGG
4844 days ago
|
|
A for loop will have bounds checking removed, for one. Also, the JIT does better inside single method bodies. Compare: 1: for(i = 0; i < arr.Length; i++) sum += arr[i];
2: foreach(var x in generate(count)) sum += x;
In the first case, you end up with a small, relatively tight loop (the machine code has a lot of extra stuff I don't quite understand).In the second case, you're literally doing a virtual call (and I don't think the CLR inlines interface calls) to get_Current() in a loop, followed by MoveNext(). So there's 2 function call overheads, not to mention the actual code that get_Current and MoveNext have. Here's the sample program[1]. I get about 600% runtime for the enumerable version versus the array. Given all the extra work, I'm sorta impressed it's only 6x. The 32-bit JIT is a bit slower doing the array method than the 64-bit, which surprises me. Here's the code for the loops[2]. 1: http://pastebin.com/GAg3RiNx 2: http://pastebin.com/index/a1eC8sX9 |
|