Skip to main content

Java 8 streams performance on mathematical calculations

Java 8 Streams API supports many parallel operations to process the data, it abstracts low level multithreading logic. To test performance did following simple test to calculate factorial of first X number starting with N.

Following program calculates factorial of first 1000 numbers.

package com.java.examples;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class MathCalculation {
 public static void main(String[] args) {
  List < Runnable > runnables = generateRunnables(1, 1000);
  Instant start = Instant.now();
  // Comment one of the lines below to test parallel or sequential streams
  runnables.parallelStream().forEach(r -> r.run());
  // runnables.stream().forEach(r -> r.run());
  Instant end = Instant.now();
  System.out.println("Calculated in " + Duration.between(start, end));
 }

 private static void factorial(int number) {
  int i;
  BigInteger fact = BigInteger.valueOf(1);
  for (i = 1; i <= number; i++) {
   fact = fact.multiply(BigInteger.valueOf(i));
  }
  System.out.println("Factorial of " + number + " is: " + fact);
 }

 private static List < Runnable > generateRunnables(Integer num, int count) {
  List < Runnable > l = new ArrayList < Runnable > ();
  for (int i = 0; i < count; i++) {
   int n = num + i;
   Runnable r = () -> {
    factorial(n);
   };
   l.add(r);
  }
  return l;
 }
}


Results:

Parallel stream -> 0.765S 
Sequential stream -> 0.849S

This is just one example to demonstrate how Streams can improve performance, there are several use cases. Also notice how Java 8 changes the way we use to write programs before this version was released.




Comments