To my understanding streams are faster than conventional old programing.
However, when I ran following code the result is something I did not expect.
public class Application {
public static void main(String[] args) {
long startTime = System.nanoTime();
int[] a = { 1, 2, 3, 4 };
int m = Arrays.stream(a).reduce(Integer.MIN_VALUE, Math::max);
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);
}
}
Output is :22857304
public class Application {
public static void main(String[] args) {
long startTime = System.nanoTime();
int[] a = { 1, 2, 3, 4 };
int e = a.length;
int m = Integer.MIN_VALUE;
for (int i = 0; i < e; i++)
if (a[i] > m)
m = a[i];
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
System.out.println(totalTime);
}
}
Output is :1459
Please help me understand why is stream so slow ?