那么,只需写一个微基准:
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)); } }
在我的机器上,版本1看起来要快一点:
版本1:5236
版本2:5477
(但是在1亿次迭代中这是0.2秒.我不关心这个.)
如果查看生成的字节码,版本2中还有两条指令可能导致执行时间更长:
public static boolean version1(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iload_1 5: getstatic #2; //Field list:[I 8: arraylength 9: if_icmpge 35 12: iload_0 13: ifne 35 16: getstatic #2; //Field list:[I 19: iload_1 20: iaload 21: getstatic #3; //Field testVal:I 24: if_icmpne 29 27: iconst_1 28: istore_0 29: iinc 1, 1 32: goto 4 35: iload_0 36: ireturn public static boolean version2(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iload_1 5: getstatic #2; //Field list:[I 8: arraylength 9: if_icmpge 39 12: iload_0 13: ifne 39 16: getstatic #2; //Field list:[I 19: iload_1 20: iaload 21: getstatic #3; //Field testVal:I 24: if_icmpne 31 27: iconst_1 28: goto 32 31: iconst_0 32: istore_0 33: iinc 1, 1 36: goto 4 39: iload_0 40: ireturn