In the context of a large client application, I often advise engineers that if we're optimizing things like the types of `for` loops we use, we've won the performance lottery. That is, I've never found a critical performance issue that is the result of using `forEach` instead of `for`.
untog|7 years ago
fvdessen|7 years ago
GordonS|7 years ago
Well, yes, but the relative difference between a for and foreach loop is miniscule - not 50x difference. In absolute terms, the overhead of both is barely measurable, and is extremely unlikely to be a bottleneck in any client-side application.
piaste|7 years ago
The issue was that the collection being iterated over was a non-generic .NET 1.0 DataTable. Using a foreach loop would implicitly box and then re-cast each object, while the for loop directly accessed the correctly typed .Item() and did not need to do that.
Ironically, the body of the loop was a fairly tricky logistics algorithm I had just written, so I had every reason to assume the problem was on the inside. Imagine my surprise when I changed it to a for loop - strictly to access the index and print out some timings - and watched the procedure suddenly become instant...