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
}
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:
(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.
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.