I was told that Java Stream is a good choice for processing a big mount of data and I did a comparison test recently. However the test result is unexpected:
The question is from CodeWar:
Suppose there is a metro with 100 people initially, on each stop there are several people get in the metro and several people get out. The target is to count the number of the people remained in the metro after a big number of stops (100000).
Here is my code:
import java.util.ArrayList;
public class Metro1 {
private final static int STOPS = 100000;
private static ArrayList<int[]> metro = new ArrayList<int[]>();
public static int sum1() {
int sum = 0;
for(int[] x: metro) {
sum +=x[0] - x[1];
}
return sum;
}
public static int sum2() {
return metro.stream()
.mapToInt(x -> x[0]-x[1])
.sum();
}
public static void main(String[] args) {
long start=0;
long end = 0;
metro.add(new int[] {100,0});
for(int i=1;i<STOPS;i++) {
int in = (int) Math.round(Math.random() * 10);
int out = (int) Math.round(Math.random() * 10);
metro.add(new int[] {in,out});
}
System.out.println("Stops: " + metro.size());
start = System.currentTimeMillis();
System.out.println("sum1: " + sum1());
end = System.currentTimeMillis();
System.out.println("sum1 (for loop): " + String.valueOf(end-start) + " milliseconds.");
start = System.currentTimeMillis();
System.out.println("sum2: " + sum2());
end = System.currentTimeMillis();
System.out.println("sum1 (stream): " + String.valueOf(end-start) + " milliseconds.");
}
}
I ran the code in Eclipse and I found that sum1 is much more faster than sum2:
Stops: 100000
sum1: 79
sum1 (for loop): 6 milliseconds.
sum2: 79
sum1 (stream): 68 milliseconds.
I thought the code is simple enough, but why the stream is slower than for loop?
Thanks,
Alex