Last active
January 28, 2017 15:46
-
-
Save SansWord/e652ef1b8a7c4dcf9f13a91c4bf6562d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running result:
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.