Consider the following two ways of writing a loop in Java to see if a list contains a given value:
Style 1
boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; }
Style 2
boolean found = false; for(int i = 0; i < list.length && !found; i++) { found = (list[i] == testVal); }
The two are equivalent, but I always use style 1 because 1) I find it more readable, and 2) I am assuming that reassigning found to false hundreds of times feels like it would take more time. I am wondering: is this second assumption true?
Nitpicker’s corner
- I am well aware that this is a case of premature optimization. That doesn’t mean that it isn’t something that is useful to know.
- I don’t care which style you think is more readable. I am only interested in whether one has a performance penalty compared to the other.
- I know that style 1 has the advantage of allowing you to also put a
break;statement in theifblock, but I don’t care. Again, this question is about performance, not style.
Well, just write a micro benchmark:
import java.util.*; public class Test { private static int[] list = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9} ; private static int testVal = 6; public static boolean version1() { boolean found = false; for(int i = 0; i < list.length && !found; i++) { if(list[i] == testVal) found = true; } return found; } public static boolean version2() { boolean found = false; for(int i = 0; i < list.length && !found; i++) { found = (list[i] == testVal); } return found; } public static void main(String[] args) { // warm up for (int i=0; i<100000000; i++) { version1(); version2(); } long time = System.currentTimeMillis(); for (int i=0; i<100000000; i++) { version1(); } System.out.println('Version1:' + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); for (int i=0; i@lt;100000000; i++) { version2(); } System.out.println('Version2:' + (System.currentTimeMillis() - time)); } }On my machine version1 seems to be a little bit faster:
Version1:5236
Version2:5477
(But that’s 0.2 seconds on a 100 million iterations. I wouldn’t care about this.)
If you look at the generated bytecode there are two more instructions in version2 which probably cause the longer execution time: