Skip to content

Instantly share code, notes, and snippets.

@SansWord
Last active January 28, 2017 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SansWord/e652ef1b8a7c4dcf9f13a91c4bf6562d to your computer and use it in GitHub Desktop.
Save SansWord/e652ef1b8a7c4dcf9f13a91c4bf6562d to your computer and use it in GitHub Desktop.
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by sansword on 2017/1/28.
*/
public class ForEachPerformanceTest {
public static void main(String[] args) {
long differenceSum = 0;
long maxDifference = 0;
int sumSum = 0;
int loopNum = 10000000;
int maxIndex = -1;
Integer[] differenceArray = new Integer[100];
Arrays.fill(differenceArray, 0);
for (int j = 0; j < loopNum; j++) {
List<Integer> input = new ArrayList<>();
for (int i = 0; i < 100; i++) {
input.add((int) (1 + Math.random() * 100));
}
long startFor = System.currentTimeMillis();
final int[] sumFor = {0};
for (Integer integer : input) {
sumFor[0] += integer;
}
long endFor = System.currentTimeMillis();
long startForEach = System.currentTimeMillis();
final int[] sumForEach = {0};
input.forEach(integer -> sumForEach[0] += integer);
long endForEach = System.currentTimeMillis();
Long singleDifference = Math.abs((endForEach - startForEach) - (endFor - startFor));
differenceSum += singleDifference;
if (singleDifference > maxDifference) {
maxDifference = singleDifference;
maxIndex = j;
}
differenceArray[singleDifference.intValue()] += 1;
sumSum += Math.abs(sumFor[0] - sumForEach[0]);
}
if (sumSum != 0) {
throw new RuntimeException("something goes wrong.");
}
System.out.println("difference sum :" + differenceSum);
System.out.println("Max difference:" + maxDifference + ", @" + maxIndex);
System.out.println("difference avg. :" + ((differenceSum + 0.0) / loopNum));
System.out.println("===== difference array =====");
for (int i = 0; i < differenceArray.length; i++) {
Integer currentDifference = differenceArray[i];
if (currentDifference > 0) {
System.out.println(i + ":" + currentDifference);
}
}
}
}
@SansWord
Copy link
Author

Running result:

difference sum :3062
Max difference:47, @0
difference avg. :3.062E-4
===== difference array =====
0:9996984
1:3015
47:1

Process finished with exit code 0

It seems stream is slow when it's used for the first time (regardless of different or same object)
Then it'll be mostly the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment