JavaToTavaL
JavaToTavaL

Reputation: 35

Is it preferable to pre-calculate condition statement part of for loop?

For example

int offset = getOffset();
int count = getCount();
int limit = count + offset;
for (int i; i < limit; i++) {}

is more preferable to

int offset = getOffset();
int count = getCount();
for (int i; i < offset + count; i++) {}

If Java VM does the addition on each iteration, that sounds like quite an overhead. But if the complier is smart enough to limit the addition to single time, I'd like to keep my code short.

Upvotes: 0

Views: 93

Answers (1)

Sweeper
Sweeper

Reputation: 271800

Premature optimization is the root of all evil.

Don't worry about this now.


When you extract the addition part out of the loop, it would indeed be evaluated only once. Some compilers may be smart enough to optimise this as well, but some may not.

The time it takes for almost all CPUs to do addition of 32 bit integers is incredibly small. If you used a profiler and found that the for loop condition is indeed causing performance problems, then you should take the addition out and see if it helps. But there is little point in worrying about it when you don't even have/haven't found a problem.


So for now, write your code according to what you are thinking in your head. For me, for example, if I am thinking "now I need to repeat this (offset + count) times...", I will write

for (int i = 0 ; i < offset + count ; i++)

If I am thinking "now I need to calculate how many times we loop for, and then I will loop that many times", then I would write:

int limit = offset + count;
for (int i = 0 ; i < limit ; i++)

Upvotes: 6

Related Questions