Summary

There are different techniques for implementing selectors and loops. Depending on the aim of a piece of code, a certain technique will be more useful than another. This chapter explained the characteristics of different techniques and showed where to use each.

  • Selectors

if..else constructions are very fast for the first few cases and increasingly slower for the rest, with the default case being the slowest. Use if..else constructions for evaluating complex expressions that cannot be reduced to a numbered range for a selector, and either/or situations that are unlikely to be augmented with additional cases in the future.

The switch statement is equally fast for all selectable cases, except for the default case, which is faster than the other cases. switch is slower than if..else only when there are a minimal number of cases. Use the switch statement wherever the selector can be reduced to a numbered range—preferably a continuous one—and the number of (expected) cases is higher than 3 or 4.

Jump tables are equally fast for each selectable function they contain. Defaults need to be coded by hand. When cases delegate all the work to a function, a jump table is even faster than a switch , as long as the selector range is continuous. Use jump tables when the selector can be reduced to a continuous numbered range and cases immediately delegate to functions.

Array lookup is the fastest technique to obtain a result based on the value of a selector. The memory usage of the array is best when the selector range is continuous. Array lookup can be used only when the selectable results can be calculated beforehand. Use array lookup when the selector can be reduced to a continuous numbered range, the footprint of the array is not a problem, and the selectable results can be calculated beforehand.

  • Loops

It is very important to keep an eye on the performance of the body statements of loops. Loops often perform hundreds of iterations, which means that each statement that can be optimized is, in effect, optimized hundreds of times over. This chapter has shown some techniques for optimizing loops and highlighted places where loops can often be optimized. It is a good idea for implementers to always keep the efficiency of their loops in mind when writing software, even when writing seemingly trivial loops. In many cases, the number of loop iterations depends on the number of elements in an array, list, or database. This number will grow over time. In other cases, loops with an initially small number of iterations are enlarged when a program is updated or reused. This means you cannot assume that a small loop will always stay a small loop.

Where possible the size and number of iterations of loops should be honed with the use of break and continue statements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset