The Bum Rap of foreach
Update: fixed the title per comments and I noticed Rico chimed in.
I had two separate interactions today where someone told me they opted for ugly\error prone for-loop code because foreach was “too slow”. There are so many things wrong with that analysis where do I start??
- In one of the cases we were iterating over an array… Google helped me quickly find this post and Kevin is right, C# and VB make foreach of arrays just peachy.
- The rationale for why foreach is “too slow” was simply “Rico said so”. Again a quick google search puts the direct facts to rest. But the meta-issue, which I am sure Rico would agree with, is that there are very few “laws” of perf. Know your scenarios and measures are the only two I think. Because rico said didn’t work for me in 2nd grade and it doesn’t work for you now either.
- Yes, fine there is something to be aware of wrt foreach over ArrayList, which I will not repeat here but to say they very often are a wash in real world scenarios and developer productivity (on-time, less bugs) is almost always a better tradeoff. In addition, you can mitigate this in your own collection types today and we have addressed it with List<T> in Whidbey.
- It is my belief most of our customers are not having significant perf issues on the platform (but I am always open to new data). That is not to say the CLR doesn’t have some perf issue we need to address (we do!), I am just saying that on balance, for the kinds of apps customers are building today the value we give far outweighs the cost. Where there are perf issues, I seriously doubt they are fixed by moving from foreach to for!
- Eric tells me Java is adding foreach because it is such a useful feature… it can’t be that bad ;-)
Go, use foreach and be proud!