For…Each loops can be nasty…

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: