user14302571
user14302571

Reputation: 43

Is one big for loop faster than than two small ones?

In the code, I have made two for loops:

for(int y = 0;i < HEIGHT; y++){
for(int y = 0;i < WIDTH; y++){
//lots of switch cases
}
}

and I wonder, is it faster to use one for loop like this? :

for(int i = 0;i < HEIGHT*WIDTH; i++){
//lots of switch cases
}

Upvotes: 2

Views: 214

Answers (2)

K.Nicholas
K.Nicholas

Reputation: 11561

No.

As mentioned, you should determine your end condition before you use in it a loop, meaning that you should have

int total = height*width;
for( int i=0; i < total; ++i ) {
    // ...
}

so that total isn't constantly computed during the loop. That said, everyone does it and I would expect the compiler to optimize your version into this version anyway.

The real issue, as I see it, is that in the loop you may have to reverse the computation from the total, meaning that you might have to have

int total = height*width;
for( int i=0; i < total; ++i ) {
    int x = total / width;
    int y = total % height;
    call(x,y);
}

This would be slower than

for( int i=0; i < width; ++i ) {
    for( int j=0; i < height; ++i ) {
        call(i,j);
    }
}

which should be faster. This does not take into consideration "branching operations" in CPU's. See Branchless Programming: Why "If" is Sloowww... and what we can do about it!.

EDIT: And yes, the most salient comment in this thread is that you should worry about readability much more performance.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140633

The usual newbie misconception: java performance doesn't come out of "clever java source code".

The key part is: the optimisations that the just-in-time compiler does at runtime. And that starts with: the JIT deciding whether code is invoked often enough to be worth optimizing.

Thus, the real answer to (most) java performance questions is:

  • write simple code that is correct and readable
  • as that enables the JIT to optimize things when necessary AND
  • it also enables you to improve your code later on, in case you really wrote code that is for this or that reason leading to performance issues

(and that 3rd point, you figure that because your users/tests unveil "bad performance", and then you did a lot of measuring to identify the true root cause of that problem)

Thus, as said: focus on writing correct code that is easy to read and understand, and do not worry about performance until much later.

Upvotes: 2

Related Questions