1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3;
18
19 import java.util.BitSet;
20 import java.util.HashSet;
21 import java.util.concurrent.TimeUnit;
22
23 import org.openjdk.jmh.annotations.Benchmark;
24 import org.openjdk.jmh.annotations.BenchmarkMode;
25 import org.openjdk.jmh.annotations.Mode;
26 import org.openjdk.jmh.annotations.OutputTimeUnit;
27 import org.openjdk.jmh.annotations.Scope;
28 import org.openjdk.jmh.annotations.State;
29
30
31
32
33 @BenchmarkMode(Mode.AverageTime)
34 @OutputTimeUnit(TimeUnit.NANOSECONDS)
35 @State(Scope.Thread)
36 public class HashSetvBitSetTest extends AbstractLangTest {
37
38 private static final int numberOfElementsToCompute = 10;
39
40 private static int[] extractIndices(final BitSet coll) {
41 final int[] result = new int[coll.cardinality()];
42 int i = 0;
43 int j = 0;
44 while ((j = coll.nextSetBit(j)) != -1) {
45 result[i++] = j++;
46 }
47 return result;
48 }
49 private static int[] extractIndices(final HashSet<Integer> coll) {
50 final int[] result = new int[coll.size()];
51 int i = 0;
52 for (final Integer index : coll) {
53 result[i++] = index.intValue();
54 }
55 return result;
56 }
57
58 @Benchmark
59 public int[] testBitSet() {
60 final BitSet toRemove = new BitSet();
61 int found = 0;
62 for (int i = 0; i < numberOfElementsToCompute; i++) {
63 toRemove.set(found++);
64 }
65 return extractIndices(toRemove);
66 }
67
68 @Benchmark
69 public int[] testHashSet() {
70 final HashSet<Integer> toRemove = new HashSet<>();
71 int found = 0;
72 for (int i = 0; i < numberOfElementsToCompute; i++) {
73 toRemove.add(found++);
74 }
75 return extractIndices(toRemove);
76 }
77
78 @Benchmark
79 public int[] timeBitSetRemoveAll() {
80 final BitSet toRemove = new BitSet();
81 final int[] array = new int[100];
82 toRemove.set(10, 20);
83 return (int[]) ArrayUtils.removeAll(array, toRemove);
84 }
85
86 @Benchmark
87 public int[] timeExtractRemoveAll() {
88 final BitSet toRemove = new BitSet();
89 final int[] array = new int[100];
90 toRemove.set(10, 20);
91 final int[] extractIndices = extractIndices(toRemove);
92 return (int[]) ArrayUtils.removeAll((Object) array, extractIndices);
93 }
94 }