jackcogdill
jackcogdill

Reputation: 5122

Do speeds of if statements in a repetitive loop affect overall performance?

If I have code that will take a while to execute, printing out results every iteration will slow down the program a lot. To still receive occasional output to check on the progress of the code, I might have:

if (i % 10000 == 0) {
    # print progress here
}

Does the if statement checking every time slow it down at all? Should I just not put output and just wait, will that make it noticeably faster at all?

Also, is it faster to do: (i % 10000 == 0) or (i == 10000)?
Is checking equality or modulus faster?

Upvotes: 1

Views: 839

Answers (1)

Petr Janeček
Petr Janeček

Reputation: 38424

In general case, it won't matter at all.

A slightly longer answer: It won't matter unless the loop is run millions of times and the other statement in it is actually less demanding than an if statement (for example, a simple multiplication etc.). In that case, you might see a slight performance drop.

Regarding (i % 10000 == 0) vs. (i == 10000), the latter is obviously faster, because it only compares, whereas the former possibility does a (fairly costly) modulus and a comparison.

That said, both an if statement and a modulus count won't make any difference if your loop doesn't take up 90 % of the program's running time. Which usually is the case only at school :). You probably spent a lot more time by asking this question than you would have saved by not printing anything. For development and debugging, this is not a bad way to go.

The golden rule for this kind of decisions:

Write the most readable and explicit code you can imagine to do the thing you want it to do. If you have a performance problem, look at wrong data structures and algorithmic choices first. If you have done all those and need a really quick program, profile it to see which part takes most time. After all those, you're allowed to do this kind of low-level guesses.

Upvotes: 1

Related Questions