Skip to content

Instantly share code, notes, and snippets.

@cogman
Created February 5, 2015 18:28
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 cogman/f892498a66557285502f to your computer and use it in GitHub Desktop.
Save cogman/f892498a66557285502f to your computer and use it in GitHub Desktop.
Benchmark of array iteration methods.
package com.tom.garbage;
import com.google.common.base.Stopwatch;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class App
{
private static volatile Integer val;
private static List<Integer> stuff = new ArrayList<>(1000);
private static Integer[] array;
static
{
for (int i = 0; i < 1000; ++i)
stuff.add(i);
array = stuff.toArray(new Integer[stuff.size()]);
}
public static void main(String[] args)
{
while (true)
{
benchmark(App::array, "Array: ");
benchmark(App::arrayIndex, "Array Index: ");
benchmark(App::iterators, "Iterators: ");
benchmark(App::index, "Index: ");
benchmark(App::stream, "Stream: ");
benchmark(App::parallelStream, "Parallel Stream: ");
System.out.println("");
}
}
private static void array()
{
for (Integer item : array)
{
val = item;
}
}
private static void arrayIndex()
{
int size = array.length;
for (int i = 0; i < size; i++)
{
val = array[i];
}
}
private static void iterators()
{
for (Integer thing : stuff)
{
val = thing;
}
}
private static void index()
{
int size = stuff.size();
for (int i = 0; i < size; i++)
{
val = stuff.get(i);
}
}
private static void stream()
{
stuff.stream().forEach((thing)->
{
val = thing;
});
}
private static void parallelStream()
{
stuff.parallelStream().forEach((thing)->
{
val = thing;
});
}
private static void benchmark(Runnable r, String name)
{
long loops = 0;
Stopwatch watch = Stopwatch.createStarted();
while (watch.elapsed(TimeUnit.MILLISECONDS) < 1000)
{
r.run();
++loops;
}
System.out.println(name + loops);
}
}
@lutischan-ferenc
Copy link

stuff.parallelStream().forEach -> stuff.parallelStream().forEachOrdered = better performance

@cogman
Copy link
Author

cogman commented Dec 31, 2022

@lutischan-ferenc This isn't a great benchmark, (live and learn). I didn't put in a warmup (I should have) and I'm not using JMH (I should be).

Either way, the point of this benchmark is to show that there's a cost to making things parallel. Also, in this particular example, doing a forEachOrdered actually changes the stream from a parallel stream back to a serial stream. The reason it's faster is because it eliminates the overhead of thread management (the non-parallel streams are even faster).

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