This question already has an answer here:
I ran below sample code in my PC running with 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));
}
its output
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
we could see the time taken difference between the first and subsequent runs.
- does it mean stream operations are cached? Is there any internal cache implemented for streams in
Java8
? - sometimes
findAny
returns different value but the time taken is almost equal to the subsequent runs not like the first run
See below
First run taken 84099 micro seconds 50000 findAny
Subseq run taken 163 micro seconds 25000 findAny
Subseq run taken 46 micro seconds 50000 findAny
Subseq run taken 52 micro seconds 25000 findAny
No, the code generated to implement the lambdas, and the classes loaded are cached.
There is no special cache for Streams.
Indeed. Nothing about the result is cached. The first time you pay a penalty for loading the code.
BTW the coding isn't really optimised until it has been run at least 10,000 times. I would run this test repeatedly for around 10 seconds before timing it.