Why is it faster to process a sorted array than an unsorted array?

今天在stackoverflow网站上看了一个投票人数最多的一个题目,为什么处理排过序的数组比没有排序的数组的速度更快。

代码如下:

import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // Generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        // !!! With this, the next loop runs faster
        Arrays.sort(data);

        // Test
        long start = System.nanoTime();
        long sum = 0;

        for (int i = 0; i < 100000; ++i)
        {
            // Primary loop
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}

我在eclipse上跑了一下该程序,分别在排序和微排序的情况下的结果:

排序的数组花费的时间:1.3s做左右;

未排序的数组花费的时间是:5.3s左右;

它们之间的效率相差了5倍左右。

这是为啥呢?

该网站上票数最多的答案提出了一个观点:branch  prediction----分支预测

You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.

Modern processors are complicated and have long pipelines. So they take forever to "warm up" and "slow down".

Is there a better way? You guess which direction the branch will go!

  • If you guessed right, you continue executing.
  • If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.

If you guess right every time, the execution will never have to stop.
If you guess wrong too often, you spend a lot of time stalling, rolling back, and restarting.

在你的面前有一个分支,但是你完全不知道往哪个方向,这时你会做什么呢?直到前一个指令完成你才会停止执行,然后你继续找到正确的路径。

有更好的方法吗?你猜猜要从哪个方向?

如果你猜对了,就继续执行;

如果猜错了,你需要冲洗管道,然后回滚到分支处;然后在开始另外一个路径。----这就是branch prediction

With a sorted array, the condition data[c] >= 128 is first false for a streak of values, then becomes true for all later values. That's easy to predict. With an unsorted array, you pay for the branching cost

通过排序的数组,data[c] >= 128有第一批错误的值,剩下的值都是正确的,很容易预测。如果是未排序的数组,你需要去花费分支花费。

 




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值