Speeding up SlowCode
For the last practical example, we can try speeding up Mr. Smith’s SlowCode
from Chapter 1, About Performance. Here, we immediately ran into a problem. To fix or change an algorithm, we must understand what the code does. This happens a lot in practice, especially when you inherit some code. Reading and understanding code that you didn’t write is an important skill.
Let’s try to understand the first part of SlowCode
. The for
loop in SlowMethod
starts counting with 2. Then, it calls ElementInDataDivides
, which does nothing as the data
list is empty. Next, SlowMethod
adds 2 to the list.
Next, i
takes the value of 3. ElementInDataDivides
checks if 3 is divisible by 2. It is not, SlowMethod
adds 3 to the list.
In the next step, i = 4, it is divisible by 2, and 4 is not added to the list. 5 is then added to the list (it is not divisible by 2 or 3), 6 is not (divisible by 2), 7 is added (not divisible by 2, 3, or 5), 8 is not (divisible...