是否会在循环的每次迭代中重新分配变量会影响性能?

Kip*_*Kip 3 java optimization

考虑以下两种在Java中编写循环的方法,以查看列表是否包含给定值:

风格1

boolean found = false;
for(int i = 0; i < list.length && !found; i++)
{
   if(list[i] == testVal)
     found = true;
}
Run Code Online (Sandbox Code Playgroud)

风格2

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)我假设,重新分配foundfalse数百倍感觉像它会花费更多的时间.我想知道:第二个假设是真的吗?

Nitpicker的角落

  • 我很清楚这是一个过早优化的案例.这并不意味着它不是有用的东西.
  • 我不在乎你认为哪种风格更具可读性.我只对与其他人相比是否有性能损失感兴趣.
  • 我知道风格1的优点是允许你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