A couple weeks ago, my team was having issues with a new version of one of our web services. It seemed that it was using up all available TCP ports on the server, thereby causing a Denial of Service.

We found the root cause of the issue... A For..Each loop!

So, For..Each loops aren't bad. The problem was what we did inside the loop. We were looping over a set of records and then reaching out to another web service. This resulted in thousands of individual web service calls back to the same web farm.

The solution:

Pull back the list first and then lookup items from that in-memory list. That reduced the number of web service calls significantly and probably improved the performance too.

Lesson learned:

Be careful what is happening inside a loop. If it involves a call to another service or SQL, then consider pulling the list back before the loop.

If you would like more info on how to avoid these types of nasty For..Each loops, please check out information on using caching technologies.