为什么`a [i] = b; i ++`比'a [i ++] = b`表现更好?

时间:2016-06-03 14:28:57

标签: java

这些天我在java中阅读DualPivotQuicksort Algorithm的源代码。我在代码中找到了一个有趣的评论。它说:

/*
 * Here and below we use "a[i] = b; i++;" instead
 * of "a[i++] = b;" due to performance issue.
 */
a[less] = ak;
++less;

我只是不知道为什么。有人能帮助我吗?

1 个答案:

答案 0 :(得分:5)

我决定比较每个选项的2 ^ 26次操作的执行时间。我迭代了4096次,得到了每个选项的平均值。

import java.util.ArrayList;

public class TestClass
{
public static void main (String[] args)
{
    long startTime, endTime;
    final int twoToPower26 = 67108864;
    int[] a1 = new int[twoToPower26];
    int[] a2 = new int[twoToPower26];
    int i = 0;
    int b = 1;
    ArrayList<Long> optionATimes = new ArrayList<Long>();
    ArrayList<Long> optionBTimes = new ArrayList<Long>();

    for (int k = 0; k < 4096; k++)
    {
        i = 0;
        //OPTION A: "a[i] = b; i++;"
        startTime = System.currentTimeMillis();
        while (i < twoToPower26)
        {
            a1[i] = b; 
            i++;
        }
        endTime = System.currentTimeMillis();
        optionATimes.add(endTime - startTime);

        i = 0;
        //OPTION B: "a[i++] = b;"
        startTime = System.currentTimeMillis();
        while (i < twoToPower26)
        {
            a2[i++] = b; 
        }
        endTime = System.currentTimeMillis();
        optionBTimes.add(endTime - startTime);
        System.out.println(k);
    }

    double averageTimeOptionA = calculateAverage(optionATimes);
    double averageTimeOptionB = calculateAverage(optionBTimes);
    System.out.println("OPTION A average time for 2^26 operations: " + averageTimeOptionA);
    System.out.println("OPTION B average time for 2^26 operations: " + averageTimeOptionB);
}

public static double calculateAverage(ArrayList<Long> times) {
    Long sum = (long) 0;
    for (Long time : times) {
        sum += time;
    }
    return sum.doubleValue() / times.size();
}
}

结果:
选项2 ^ 26次操作的平均时间:105.9140625 ms
选项B 2 ^ 26次操作的平均时间:105.846923828125 ms

每个选项的平均时间差异在2 ^ 26次迭代中仅为67纳秒,在这种情况下,选项B略快。

我觉得这几乎可以肯定地表明性能没有差异。编译器很可能会解释每个选项。