我几天前才这样做;我们必须对一个非常大的数组求和,并且想知道最快的方法是什么——所以我测量了(不要猜;我用过jmh):
@State(Scope.Thread)
public static class Holder {
@Param({ "1000", "10000", "50000", "100000", "1000000" })
public int howManyEntries;
int array[] = null;
@Setup
public void setUp() {
array = new int[howManyEntries];
for (int i = 0; i < howManyEntries; ++i) {
array[i] = i;
}
}
@TearDown
public void tearDown() {
array = null;
}
}
@Fork(1)
@Benchmark
public int iterative(Holder holder) {
int total = 0;
for (int i = 0; i < holder.howManyEntries; ++i) {
total += holder.array[i];
}
return total;
}
@Fork(1)
@Benchmark
public int stream(Holder holder) {
return Arrays.stream(holder.array).sum();
}
@Fork(1)
@Benchmark
public int streamParallel(Holder holder) {
return Arrays.stream(holder.array).parallel().sum();
}
获胜者是总是老式的 java-7 方式。
// 1000=[iterative, stream, streamParallel]
// 10000=[iterative, stream, streamParallel]
// 50000=[iterative, stream, streamParallel]
// 100000=[iterative, stream, streamParallel]
// 1000000=[iterative, stream, streamParallel]
即使是 100 万个元素。但结果会在 60 毫秒内有所不同 - 是否会咬你完全是你的选择。
流并不意味着速度,它们不会取代旧样式,它们也不想 - 例如,它可以为您的代码增加额外的可见性。