comparing loop hoisting in .net
8 Nov 2009 1:24:23 EST

During the same WAN Party that I built howdyougetthatscar.com I also got into an argument with John Bristowe and Phil Haack about, in succession, the foreach loop, IEnumerable, yield return, and then LINQ - and my mostly-unjustified hatred for all of them. Especially the foreach loop. I really hate that thing.

Anyway, I didn't exactly justify myself well on these topics, so my plan this weekend was to write a long blog post explaining and proving that the foreach loop is to efficiency what the goto is to programmer sanity. But somehow I got sidetracked, and before I knew it I was actually using the extremely frightening WinDbg - something I had only seen the likes of crazy haskell programmers using.

WinDbg intimidating me.

The result of this epic sidetrack was somehow that I ended up comparing loop hoisting.

for(i=0; i<collection.Count; i++) 
int c=collection.Count; 
for(i=0; i<c; i++)

So if you want to take an adventure through IL all the way down to the Assembly, and find out which one is actually more efficient follow me down the rabbit hole. The answer will surprise you.

Add a comment...
required, hidden, gravatared

required, markdown enabled (help)
you type:you see:
[stolen from reddit!](http://reddit.com)stolen from reddit!
* item 1
* item 2
* item 3
  • item 1
  • item 2
  • item 3
> quoted text
quoted text
Lines starting with four spaces
are treated like code:

    if 1 * 2 < 3:
        print "hello, world!"
Lines starting with four spaces
are treated like code:
if 1 * 2 < 3:
    print "hello, world!"