I generate int numbers with and without IntSteam, surprising to me is the fact that on my machine my code runs slower with IntStream. Can someone explain why an IntStream is slower and why we need it at all although it comesup with perfomance penalty?
import java.util.Random;
import java.util.stream.IntStream;
public class Main {
private static Random r = new Random();
private static int sum;
private static int branchDirection = 500000;
private final static LIMIT = 1000000;
public static void main(String[] args) {
// int[] randomValues= getRandomValuesWithIntStream(); // This is slower
int[] randomValues = getRandomValuesAsUsual(); // Than this
Arrays.sort(randomValues);
long start = System.nanoTime();
for(int i = 0;i<randomValues.length; i++) {
if (randomValues[i] >branchDirection) {
sum += randomValues[i];
}
}
System.out.println("Elapsed Time: "+ (System.nanoTime()-start));
}
private static int[] getRandomValuesAsUsual() {
int[] randomValues = new int[LIMIT];
for(int i = 0;i<randomValues.length; i++) {
randomValues[i] = r.nextInt();
}
return randomValues;
}
private static int[] getRandomValuesWithIntStream() {
return IntStream.generate(r::nextInt).limit(LIMIT).toArray();
}
}