Optimize Inner Loops

Optimize those code fragments where the algorithm spends most of its time.
Often these fragments
are inside loops.

Overall code organization:

	lineMethod( )
	{
	    // 1. general set up
	    // 2. special case set up
	    while (notdone) {
	        // 3. inner loop
	    }
	}
  • remove unnecessary method invocations
    replace Math.round(m*x0 + b)
    with (int)(m*x0 + b + 0.5)
    Does this always work?
  • use incremental calculations

    Consider the expression
        y = (int)(m*x + b + 0.5)

    The value of y is known at x0 (i.e. it is y0 + 0.5)
    Future values of y can be expressed in terms of previous values with a difference equation:
    yi+1 = yi + m;
    or
    yi+1 = yi - m;

Lecture 5   Slide 8   6.837 Fall '00