灵感来自这个问题:
Why is it faster to process a sorted array than an unsorted array?
Why is it faster to process a sorted array than an unsorted array?
我写了自己的分支预测实验:
- public class BranchPrediction {
- public static void main(final String[] args) {
- long start;
- long sum = 0;
- /* No branch */
- start = System.nanoTime();
- sum = 0;
- for (long i = 0; i < 10000000000L; ++i)
- sum += i;
- System.out.println(System.nanoTime() - start);
- System.out.println(sum);
- /* With branch */
- start = System.nanoTime();
- sum = 0;
- for (long i = 0; i < 10000000000L; ++i)
- if (i >= 0)
- sum += i;
- System.out.println(System.nanoTime() - start);
- System.out.println(sum);
- /* No branch (again) */
- start = System.nanoTime();
- sum = 0;
- for (long i = 0; i < 10000000000L; ++i)
- sum += i;
- System.out.println(System.nanoTime() - start);
- System.out.println(sum);
- /* With branch (again) */
- start = System.nanoTime();
- sum = 0;
- for (long i = 0; i < 10000000000L; ++i)
- if (i >= 0)
- sum += i;
- System.out.println(System.nanoTime() - start);
- System.out.println(sum);
- }
- }
结果让我感到困惑:根据程序输出,带分支的循环比没有分支循环的循环可靠得快.
输出示例:
- 7949691477
- -5340232226128654848
- 6947699555
- -5340232226128654848
- 7920972795
- -5340232226128654848
- 7055459799
- -5340232226128654848
为什么会这样?
编辑:
>反汇编类显示Java编译器没有优化(遗漏)任何东西(https://gist.github.com/HouzuoGuo/5692424)
> Why is it faster to process a sorted array than an unsorted array?作者使用的Java基准技术与我的相同.
>该机器是Intel核心i7,运行Linux 3.2 64位和Oracle JVM 1.7 64位
>当我超过循环迭代的次数时,with-branch循环比非分支循环运行多SECONDS.