我有一个非常简单的程序
package t;
public class T {
public static void main(String[] args) {
for (int i =0; i<10; i++) {
java.util.List<Character> l = java.util.Arrays.asList('1', '2', 'a', 'b', '3', '4', 'p');
java.time.Instant then = java.time.Instant.now();
java.util.List<Character> numbers1 = l.stream().filter(Character::isDigit).collect(java.util.stream.Collectors.toList());
long streamTime = java.time.Duration.between(then, java.time.Instant.now()).toNanos();
then = java.time.Instant.now();
java.util.List<Character> numbers = new java.util.ArrayList<>();
for (Character c : l) {
if (Character.isDigit(c)) {
numbers.add(c);
}
}
long forLoopTime = java.time.Duration.between(then, java.time.Instant.now()).toNanos();
System.out.println(numbers + " For Time taken " + forLoopTime + " Stream Time " + streamTime);
}
}
}
在Java 8中执行时,以下是 o/p
爪哇吨/吨
[1, 2, 3, 4] For Time taken 0 Stream Time 54000000
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 1000000 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
[1, 2, 3, 4] For Time taken 0 Stream Time 0
在java 16中执行相同
java t/T.java
[1, 2, 3, 4] For Time taken 37000 Stream Time 701000
[1, 2, 3, 4] For Time taken 6000 Stream Time 31000
[1, 2, 3, 4] For Time taken 6000 Stream Time 12000
[1, 2, 3, 4] For Time taken 5000 Stream Time 11000
[1, 2, 3, 4] For Time taken 5000 Stream Time 12000
[1, 2, 3, 4] For Time taken 7000 Stream Time 19000
[1, 2, 3, 4] For Time taken 6000 Stream Time 18000
[1, 2, 3, 4] For Time taken 7000 Stream Time 18000
[1, 2, 3, 4] For Time taken 7000 Stream Time 14000
[1, 2, 3, 4] For Time taken 6000 Stream Time 20000
在java 11中执行时
java t/T.java
[1, 2, 3, 4] For Time taken 40000 Stream Time 461000
[1, 2, 3, 4] For Time taken 7000 Stream Time 39000
[1, 2, 3, 4] For Time taken 5000 Stream Time 17000
[1, 2, 3, 4] For Time taken 10000 Stream Time 20000
[1, 2, 3, 4] For Time taken 9000 Stream Time 33000
[1, 2, 3, 4] For Time taken 8000 Stream Time 22000
[1, 2, 3, 4] For Time taken 8000 Stream Time 36000
[1, 2, 3, 4] For Time taken 6000 Stream Time 17000
[1, 2, 3, 4] For Time taken 6000 Stream Time 14000
[1, 2, 3, 4] For Time taken 5000 Stream Time 22000
这表明无论我们使用哪个版本的 JDK,流都比基本的 for 循环慢。我的理解正确吗?我的印象是 JDK 8 可能会更慢,但在更高版本的 JDK 中不会。