I am just starting to learn about the Streams and parallel in Java and I was wondering why a normal for loop takes less time than IntStream paralleled at adding items to an array.
package parallel; import java.util.stream.IntStream; public class Parallel { public static void main(String[] args) { final int[] intArray = new int[100000]; long startTime = System.currentTimeMillis(); IntStream.range(0, 100000).parallel().forEach(i -> intArray[i]=i); long endTime = System.currentTimeMillis(); System.out.println("Parallel time: " + (endTime-startTime)); final int[] intArray2 = new int[100000]; try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } startTime = System.currentTimeMillis(); for(int i = 0; i < 100000; i++){ intArray2[i] = i; } endTime = System.currentTimeMillis(); System.out.println("Non parallel time: " + (endTime-startTime)); } } Getting results like this.
Parallel time: 110
Non parallel time: 7
intArrayandintArray2), so both cases start from a "clean" array.