Efficient Loop Construction

Performance problems that might appear small or insignificant can swell to application-crippling sizes when those problems are executed within a loop or are executed by hundreds or thousands of users simultaneously. Loops act like a magnifying glass for small performance problems and can make them considerably larger.

One of the most common loop mistakes is in invoking an additional cost during loop iterations. Take the following loop for example:

for (int x=0; x < myObject.GetItems().Count; x++) {     // perform task } 

There are two main problems with the preceding loop:

  • The maximum bound of the loop could be changed by the code within the loop, creating unpredictable results. For example, if the code within the loop adds an item to the list of items returned by myObject.GetItems(), the loop could end up being infinite or running for longer than expected.

  • The call to GetItems() could potentially take a long time. Placing this call within the for statement invokes this method during every single loop iteration. If GetItems() not only takes a long time to execute but returns a large number of items, the loop could take an extremely long time to execute.

A better way to rewrite the preceding loop would be to place the GetItems() call at the beginning of the loop to guarantee consistency in the list of items as well as to incur the overhead cost of the method only once rather than once per iteration:

List<CustomObject> list = myObject.GetItems(); int maxBound = list.Count; for (int x=0; x < maxBound; x++) {      // perform task on 'list' variable } 

Even accessing the Count property of a list still costs more than accessing a previously defined int variable. The preceding code might have more lines than the first example, but this code runs faster. By pulling expensive calculations out of the loop and performing them before the loop begins, you incur the cost only once instead of once per iteration. In terms of computer science notation, the cost of the GetItems() method is "O(N)" (operational cost is directly related to the number of items in the loop) when placed inside the loop, and "O(1)" (operational cost only incurred once) when placed before the loop.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net