I was just trying out a few code snippets and came across an observation where using simple for loop gave me better performance results compared to using java 8 stream. Now, I may have missed something in understanding these things. I need help understanding the difference. Adding my code below.
//Following takes almost 3ms
public int[] testPerf(int[] nums, int[] index) {
List<Integer> arrayL = new ArrayList<>();
for(int i =0; i< index.length; i++){
arrayL.add(index[i], nums[i]);
}
return arrayL.stream().mapToInt(i -> i).toArray();
}
//Following takes almost 1ms
public int[] testPerf(int[] nums, int[] index) {
List<Integer> arrayL = new ArrayList<>();
for(int i =0; i< index.length; i++){
arrayL.add(index[i], nums[i]);
}
int [] result = new int[index.length];
for(int i =0; i< index.length; i++){
result[i] = arrayL.get(i);
}
return result;
}
EDIT: START
What am I trying to test? Injecting elements of nums at indexes specified by index array to form a final result.
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
EDIT: END
Note that I have tested these with different inputs and tried arrays containing 2k+ elements but still the code with for loop gave me better performance.
Please guide what is it that makes the other code take more time? Also point out to any references where I can learn when NOT to use java streams? (When not to overcomplicate? :) )