The most important code fragments to consider when optimizing are those where the algorithm spends most of its time. Often these areas are within loops.
Our improved algorithm can be partitioned into two major sections. The first section is basically set-up code that is used by the second section, the central pixel-drawing while-loop. Most of the pixels are drawn in this while loop.
First optimization: remove unnecessary method invocations. Notice the call to the round class-method of the Math object that is executed for each pixel drawn. You might think that proper rounding is so trival a task that it hardly warrants a special method to begin with. But, it is complicated when differences between postive and negative numbers, and proper handling of fractions with a value of exactly 0.5 are considered. However, in our line drawing code we are either not going to run into these cases (i.e. we only consider positive coordinate values) or we don't care (i.e. we don't expect to see values of 0.5 very often, and when we do we'd like to see them handled consistently). So for our purposes the call to Math.round(m*x0 + b) could be replaced with the following (int)(m*y0 + b + 0.5).
Second optimization: use incremental calculations. Incremental or iterative function calculations use previous function values to compute future values. Often expressions within loops depend on a value that is being incremented or decremented on each loop iteration. In these cases the actual function values might be more efficiently calculated by first computing an initial value of the function during the loop set up, and updating the subsequent function values using a discrete version of a differential equation called a difference equation.
Consider the expression,