小编Ign*_*tyo的帖子

为什么对已排序数组求和比对未排序数组求和更快?

我有一个ArrayList,其中的数字从 10 MM 到 20 MM

 List<Long> l = new ArrayList<>();
        for (long i = 10_000_000; i < 20_000_000; i++) {
            l.add(i);
        }
Run Code Online (Sandbox Code Playgroud)

为什么sum()函数在排序数组上比在未排序数组上更快?

public class Main {

    public static void main(String[] args) {
        List<Long> l = new ArrayList<>();
        for (long i = 10_000_000; i < 20_000_000; i++) {
            l.add(i);
        }

        System.out.println(sum(l));

        Collections.shuffle(l);
        System.out.println(sum(l));

        Collections.sort(l);
        System.out.println(sum(l));
    }

    static long sum(List<Long> l) {
        long started = System.nanoTime();
        long result = 0;
        for (long v : l) { …
Run Code Online (Sandbox Code Playgroud)

java arrays sorting cpu benchmarking

1
推荐指数
1
解决办法
316
查看次数

标签 统计

arrays ×1

benchmarking ×1

cpu ×1

java ×1

sorting ×1