-
Notifications
You must be signed in to change notification settings - Fork 1
/
StreamVsLoopsBenchmark.java
87 lines (74 loc) · 1.76 KB
/
StreamVsLoopsBenchmark.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.patotski.performance.collections;
import com.patotski.performance.array.PrimitiveVsWrapperBenchmarks;
import com.patotski.performance.utils.BenchmarkUtils;
import org.openjdk.jmh.annotations.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@BenchmarkMode({Mode.AverageTime})
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 3, time = 5, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
public class StreamVsLoopsBenchmark {
private List<Integer> list;
@Param({ "100000" })
private int size;
@Setup
public void setup() {
list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(i);
}
}
@Benchmark
public int stream() {
return list.stream()
.filter(i -> i == -1)
.findAny()
.orElse(0);
}
@Benchmark
public int streamParallel() {
return list.stream()
.parallel()
.filter(i -> i == -1)
.findAny()
.orElse(0);
}
@Benchmark
public int loop() {
for (Integer i : list) {
if (i == -1) {
return i;
}
}
return 0;
}
@Benchmark
public int iterator() {
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer i = iterator.next();
if (i == -1) {
return i;
}
}
return 0;
}
@Benchmark
public int oldSchoolForLoop() {
int listSize = list.size();
for (int i = 0; i < listSize; i++) {
if (list.get(i) == -1) {
return i;
}
}
return 0;
}
public static void main(String[] args) throws Exception {
BenchmarkUtils.runBenchmark(StreamVsLoopsBenchmark.class);
}
}