JDK 正在引入一个Stream.toList()带有JDK-8180352的 API 。这是一个基准代码,我试图将其性能与现有的进行比较Collectors.toList:
@BenchmarkMode(Mode.All)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 20, time = 1, batchSize = 10000)
@Measurement(iterations = 20, time = 1, batchSize = 10000)
public class CollectorsVsStreamToList {
@Benchmark
public List<Integer> viaCollectors() {
return IntStream.range(1, 1000).boxed().collect(Collectors.toList());
}
@Benchmark
public List<Integer> viaStream() {
return IntStream.range(1, 1000).boxed().toList();
}
}
Run Code Online (Sandbox Code Playgroud)
结果总结如下:
Benchmark Mode Cnt Score Error Units
CollectorsVsStreamToList.viaCollectors thrpt 20 17.321 ± 0.583 ops/s
CollectorsVsStreamToList.viaStream thrpt 20 23.879 ± 1.682 ops/s
CollectorsVsStreamToList.viaCollectors avgt 20 0.057 ± …Run Code Online (Sandbox Code Playgroud) toList() 的实现明确返回一个 ArrayList,它确实保证了可变性:
public static <T>
Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>(ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
Run Code Online (Sandbox Code Playgroud)
但是 toList 的 JavaDoc 是这样的:
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new {@code List}. There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code List} returned; if more
* control over the returned {@code List} is required, use {@link #toCollection(Supplier)}.
*
* …Run Code Online (Sandbox Code Playgroud) java ×2
java-stream ×2
collections ×1
collectors ×1
java-16 ×1
java-8 ×1
jmh ×1
performance ×1