Stuff that's in my head

Can open... Worms? everywhere! The blog of Colin Angus Mackay
posts - 379, comments - 486, trackbacks - 51

Tip of the Day #15: Loop Performance

When you look at the code it will probably seem somewhat obvious, but it is interesting how the same thought process isn’t necessarily there when actually developing the code, especially when under the pressure of a looming deadline.

Take for example this snippet of code (from a fictitious hotel management system) that may have been run by a receptionist to print out the check in forms that customers of the hotel will fill in on their arrival.

List bookings = GetTodaysBookings();

foreach (Booking booking in bookings)
{
    PrintService service = GetLocalPrintService();
    service.PrintCheckInForm(booking);
}

The method GetLocalPrintService() could be doing a multitude of things. It may simply be creating a new instance of the PrintService object, or it could be resolving a number of dependencies in order to set itself up to communicate with the local printer. But what ever it is doing, we don’t actually need a new instance of the service on each loop. The code will work just as well if we have just one instance that is re-used on each iteration of the loop.

That being the case, the creation of the PrintService can be moved outside the loop so it is created only once, thus removing unnecessary work from the loop. The new code then looks like this:

List bookings = GetTodaysBookings();
PrintService service = GetLocalPrintService();

foreach (Booking booking in bookings)
{
    service.PrintCheckInForm(booking);
}

As I said at the top, this is obvious. Isn't it?

Print | posted on Monday, September 07, 2009 7:55 AM

Feedback

Gravatar

# re: Tip of the Day #15: Loop Performance

Call me a picky bastard but I'd seriously consider a first written warning to any programmer who needed me to point this out! But it's an excellent point and it never hurts to reiterate the obvious now and then.
9/7/2009 8:16 AM | Rob Manderson

# re: Tip of the Day #15: Loop Performance

obvious but something i find myself checking and refactoring now and then!
9/7/2009 9:22 AM | Guy Harwood
Gravatar

# re: Tip of the Day #15: Loop Performance

@Rob: I'll consider myself duly warned then. :)

@Guy: Indeed that's what prompted this post. I noticed I did this refactoring on code that I had written a couple of days previously and I was thinking to myself "What was I thinking when I wrote that?!" It was such an obvious school-boy error.
9/7/2009 10:48 AM | Colin Mackay

Post Comment

Title  
Name  
Email
Url
Comment   

Powered by: