Parallel Streams Performance Testing

In this lesson, we will explore the performance of Parallel Streams VS Regular Streams program execution.

Let’s create two methods for summing the integers. One method will use regular Streams and the other will use Parallel Streams. The summation will be performed in a loop, 10 times, in both methods.

  private static void sumWithRegularStream() {
    for (int i = 0; i < 10; i++) {
      IntStream.rangeClosed(1, 100000).sum();
    }
  }

  private static void sumWithParallelStream() {
    for (int i = 0; i < 10; i++) {
      IntStream.rangeClosed(1, 100000).parallel().sum();
    }
  }


Now let’s call these methods and find out how long does it takes for both methods to execute the operations:

class Test {

  public static void main(String[] args) {
    long regularStreamStartTime = System.currentTimeMillis();

    sumWithRegularStream();

    System.out.println("Regular Stream execution time taken: " + (System.currentTimeMillis() - regularStreamStartTime));

    long parallelStreamStart = System.currentTimeMillis();

    sumWithParallelStream();

    System.out.println("Parallel Stream execution time taken: " + (System.currentTimeMillis() - parallelStreamStart));
  }

  private static void sumWithRegularStream() {

    for (int i = 0; i < 10; i++) {
      IntStream.rangeClosed(1, 100000).sum();
    }
  }

  private static void sumWithParallelStream() {
    for (int i = 0; i < 10; i++) {
      IntStream.rangeClosed(1, 100000).parallel().sum();
    }
  }
}
Output: Regular Stream execution time taken: 15 Parallel Stream execution time taken: 7

You see that executing the above operations with Parallel Streams took less time, than with regular Streams.

Note: This depends on what machine you are running the above program. Your CPU should have at least 4 cores with 2 threads to see the difference. In other cases, you may see that the Parallel Streams took more time to execute than the regular Streams because of the lack of threads.

That was all about exploring the performance of the Parallel Streams in Java. Proceed to the next lesson.

Happy Learning!

Leave a Reply

Your email address will not be published. Required fields are marked *