Skip to content

Instantly share code, notes, and snippets.

@spullara
Created September 14, 2012 03:02
Show Gist options
  • Save spullara/3719563 to your computer and use it in GitHub Desktop.
Save spullara/3719563 to your computer and use it in GitHub Desktop.
For vs ForEach microbenchmark
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