Created
September 14, 2012 03:02
-
-
Save spullara/3719563 to your computer and use it in GitHub Desktop.
For vs ForEach microbenchmark
This file contains 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 spullara.util; | |
import java.util.ArrayList; | |
public class Benchmarks { | |
private static int i = 0; | |
private static long time(String name, int times, Runnable runnable) { | |
long total = 0; | |
for (int i = times - 1; i >= 0; i--) { | |
long start = System.nanoTime(); | |
runnable.run(); | |
total += System.nanoTime() - start; | |
} | |
System.out.println(name + ": " + total); | |
return total; | |
} | |
public static void main(String[] args) { | |
ArrayList<String> list = new ArrayList<>(); | |
int SIZE = 1000; | |
for (int i = 0; i < SIZE; i++) { | |
list.add("Test"); | |
} | |
int times = 1000000; | |
time("total", 100, () -> { | |
compare("for/forEach", time("for", times, () -> { | |
for (String s : list) { | |
i++; | |
} | |
}), time("forEach", times, () -> { | |
list.forEach(l -> { | |
i++; | |
}); | |
})); | |
}); | |
} | |
private static void compare(String name, double aFor, double forEach) { | |
System.out.println(name + ": " + (aFor / forEach)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment