我有一个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)