Reputation: 21
I am doing something like this:
The first scenario:
for(int i=0; i<50; i++){
// execute some other code here
switch(myCustomInt){
case 1:
case 2:
case 3:
// execude method1
break;
case 4:
// execute method2
break;
}
}
The second scenario:
for(int i=0; i<50; i++){
// execute some other code here
}
switch(myCustomInt){
case 1:
case 2:
case 3:
for(int i=0; i<50; i++){
// execute method1
}
break;
case 4:
for(int i=0; i<50; i++){
// execute method2
}
break;
}
The Question:
The first scenario runs the for loop only once, but check the switch statement 50 times.
The second scenario runs the for loop twice, but check the switch statement only once.
Which is a better way to execute? I know in today's technology, the difference is most likely negligible. But I am still curious which one is, theoretically, the better way to execute it?
Thank you!
Upvotes: 1
Views: 1325
Reputation: 1075189
Note that there is a semantic difference in terms of when method1
and method2
are called for (say) i == 42
relative to the "other code" in the for
loop: In the first, method1
/method2
are called for the i == 42
iteration before "other code" for all of the i == 43
through i == 49
iterations is done. In the second, all of the "othe code" for the 50 loop iterations is done before the first call to either method1
or method2
.
Other than that semantic difference, it really doesn't matter. Do what's most readable and maintainable. That probably means the first one, but what's "readable and maintainable" varies from person to person. Elliott's point that the second one repeats the loop header an additional two times is well-taken: It opens the door to a bug caused by changing one of the three and not one or both of the other two.
Performance: It's not going to matter. The first requires that the switch (myCustomInt)
be evaluated 49 times more than the second. In theory, that evaluation costs time. In practice, I bet you'd have a really, really hard time measuring a difference, particularly if HotSpot (the Oracle Java runtime) decides this is a hotspot and aggressively optimizes it.
Upvotes: 1