I want to test how much faster Java8 parallel stream so I wrote a program .The program count the number of prime numbers in a given list of numbers. The program counts prime numbers in there ways:
- using for loop;
- by using lambda expression;
- by using lambda expression(parallel stream).
Before executing the program I was expecting that parallel stream version should be faster. But the result is
Total prime no found 664579 in 4237 mili sec ----for loop version
Total prime no found 664579 in 2440 mili sec ----parallel stream
Total prime no found 664579 in 2166 mili sec ----lambda expression
My doubt is why parallel version is slower then lambda version
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
numbers.add(i);
}
Stopwatch stopwatch = Stopwatch.createStarted();
int counter = 0;
for (int number : numbers) {
if (isPrime(number)) {
counter++;
}
}
stopwatch.stop();
System.out.println("Total prime no found " + counter + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " mili sec");
stopwatch = Stopwatch.createStarted();
long count1 = numbers.parallelStream().filter(n -> isPrime(n)).count();
stopwatch.stop();
System.out.println("Total prime no found " + count1 + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " mili sec");
stopwatch = Stopwatch.createStarted();
long count2 = numbers.stream().filter(n -> isPrime(n)).count();
System.out.println("Total prime no found " + count2 + " in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " mili sec");
stopwatch.stop();
The above program uses google Guava library to calculate time elapsed.
count1
andcount2
are identical... – Brian S