我在运行.nodes()
Intel(R) Xeon(R) CPU E5-2680 0 @ 2.70GHz (2 CPUs), ~2.7GHz
其输出
String format = "%7s run taken %6d micro seconds %5d findAny";
// First run
long start = System.nanoTime();
int rand = IntStream.range(0, 100000).parallel().findAny().getAsInt();
long end = System.nanoTime();
System.out.println(String.format(format, "First", ((end - start) / 1000), rand));
// Subsequent runs
for (int i = 0; i < 25; i++) {
start = System.nanoTime();
rand = IntStream.range(0, 100000).parallel().findAny().getAsInt();
end = System.nanoTime();
System.out.println(String.format(format, "Subseq", ((end - start) / 1000), rand));
}
我们可以看到第一次和后续运行之间的时间差异。
First run taken 92532 micro seconds 50000 findAny
Subseq run taken 61 micro seconds 50000 findAny
Subseq run taken 37 micro seconds 50000 findAny
Subseq run taken 52 micro seconds 50000 findAny
Subseq run taken 42 micro seconds 50000 findAny
Subseq run taken 33 micro seconds 50000 findAny
Subseq run taken 32 micro seconds 50000 findAny
Subseq run taken 34 micro seconds 50000 findAny
Subseq run taken 33 micro seconds 50000 findAny
Subseq run taken 34 micro seconds 50000 findAny
Subseq run taken 32 micro seconds 50000 findAny
Subseq run taken 32 micro seconds 50000 findAny
Subseq run taken 46 micro seconds 50000 findAny
Subseq run taken 36 micro seconds 50000 findAny
Subseq run taken 31 micro seconds 50000 findAny
Subseq run taken 43 micro seconds 50000 findAny
Subseq run taken 34 micro seconds 50000 findAny
Subseq run taken 31 micro seconds 50000 findAny
Subseq run taken 32 micro seconds 50000 findAny
Subseq run taken 37 micro seconds 50000 findAny
Subseq run taken 45 micro seconds 50000 findAny
Subseq run taken 49 micro seconds 50000 findAny
Subseq run taken 32 micro seconds 50000 findAny
Subseq run taken 31 micro seconds 50000 findAny
Subseq run taken 31 micro seconds 50000 findAny
Subseq run taken 37 micro seconds 50000 findAny
?Java8
会返回不同的值,但所用的时间几乎等于后续的运行,而不是第一次运行见下文
findAny
答案 0 :(得分:1)
是否意味着流操作被缓存?
不,为实现lambdas而生成的代码以及加载的类都是缓存的。
Java8中是否为流实现了内部缓存?
Streams没有特殊的缓存。
有时findAny会返回不同的值,但所用的时间几乎等于后续的运行,而不像第一次运行
事实上。没有关于结果的任何内容被缓存。您第一次为加载代码支付罚金。
BTW编码在运行至少10,000次之前并未真正优化。我会在计时之前反复运行这个测试大约10秒钟。