考虑以下两种在Java中编写循环的方法,以查看列表是否包含给定值:
boolean found = false;
for(int i = 0; i < list.length && !found; i++)
{
if(list[i] == testVal)
found = true;
}
Run Code Online (Sandbox Code Playgroud)
boolean found = false;
for(int i = 0; i < list.length && !found; i++)
{
found = (list[i] == testVal);
}
Run Code Online (Sandbox Code Playgroud)
这两者是等价的,但我总是使用方式1,因为1)我觉得它更具可读性,和2)我假设,重新分配found到false数百倍感觉像它会花费更多的时间.我想知道:第二个假设是真的吗?
break;在if块中加上一个声明,但我不在乎.同样,这个问题是关于表现,而不是风格.小智 8
那么,只需写一个微基准:
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