Performance

At this point in the book, there isn't a whole lot to say about performance, except that you should try to maximize it at all times. While a program may be "fast enough" for your current needs on your current computer, you may later need to run it using much larger inputs or on a slower computer with less memory.

Maximizing performance is mainly a matter of choosing the best algorithms and the fastest compiled programming language. Generally, shorter code is faster code, so set out from the start to learn how to write the most concise and efficient code possible. There are also some additional tricks we can use if we understand how computer hardware works. Some are portable and some are not. These tricks will be covered in the appropriate context throughout the remaining chapters.

Polynomial Factoring

Multiplication is far more expensive than addition. We can sometimes alter code to reduce the number of multiplication operations, such as by factoring polynomials:

// 6 multiplications, some of which are redundant
y = 3.0 * x * x * x + 2.0 * x * x + 1.0 * x + 5.0;

// Only 4 multiplications after factoring out x
y = x * (3.0 * x * x + 2.0 * x + 1.0) + 5.0;

// Only 3 multiplications after factoring out another x
y = x * (x * (3.0 * x + 2.0) + 1.0) + 5.0;
    
Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. How do we maximize performance of a program?