Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package benchmarks;
import org.openjdk.jmh.annotations.*;
import java.util.*;
import java.util.concurrent.*;
@Fork(value = 1)
@Warmup(iterations = 5, time = 3)
@Measurement(iterations = 10, time = 3)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class StreamVsLoopLanger {
@Param({"500000"})
// @Param({"1000", "100000", "10000000"})
private int length;
private int[] ints;
@Setup
public void setup() {
ints = ThreadLocalRandom.current().ints(length).toArray();
}
@Benchmark
public int findMaxForLoopLanger() {
int[] a = ints;
int e = ints.length;
int m = Integer.MIN_VALUE;
for (int i = 0; i < e; i++)
if (a[i] > m) m = a[i];
return m;
}
@Benchmark
public int findMaxStream() {
return Arrays.stream(ints)
.reduce(Integer.MIN_VALUE, Math::max);
}
@Benchmark
public int findMaxStreamParallel() {
return Arrays.stream(ints)
.parallel()
.reduce(Integer.MIN_VALUE, Math::max);
}
}
/*
Results for 1000, 100_000, 10_000_000 in nanoseconds
Benchmark (length) Mode Cnt Score Error Units
StreamVsLoopLanger.findMaxForLoopLanger 1000 avgt 10 369,186 ± 4,529 ns/op
StreamVsLoopLanger.findMaxForLoopLanger 100000 avgt 10 19845,077 ± 289,484 ns/op
StreamVsLoopLanger.findMaxForLoopLanger 10000000 avgt 10 3711871,012 ± 49942,887 ns/op
StreamVsLoopLanger.findMaxForLoopNormal 1000 avgt 10 209,819 ± 1,989 ns/op
StreamVsLoopLanger.findMaxForLoopNormal 100000 avgt 10 19769,689 ± 280,703 ns/op
StreamVsLoopLanger.findMaxForLoopNormal 10000000 avgt 10 3715386,078 ± 25319,267 ns/op
StreamVsLoopLanger.findMaxStream 1000 avgt 10 524,544 ± 6,854 ns/op
StreamVsLoopLanger.findMaxStream 100000 avgt 10 48092,234 ± 2998,737 ns/op
StreamVsLoopLanger.findMaxStream 10000000 avgt 10 6393546,822 ± 44090,159 ns/op
StreamVsLoopLanger.findMaxStreamParallel 1000 avgt 10 28137,221 ± 1316,457 ns/op
StreamVsLoopLanger.findMaxStreamParallel 100000 avgt 10 33863,617 ± 656,033 ns/op
StreamVsLoopLanger.findMaxStreamParallel 10000000 avgt 10 1303320,663 ± 15932,859 ns/op
Results for 500_000 in milliseconds
Benchmark (length) Mode Cnt Score Error Units
StreamVsLoopLanger.findMaxForLoopLanger 500000 avgt 10 0,099 ± 0,001 ms/op
StreamVsLoopLanger.findMaxStream 500000 avgt 10 0,237 ± 0,003 ms/op
StreamVsLoopLanger.findMaxStreamParallel 500000 avgt 10 0,059 ± 0,002 ms/op
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.