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
50
51 private static int[] extractIndices(final HashSet<Integer> coll) {
52 final int[] result = new int[coll.size()];
53 int i = 0;
54 for (final Integer index : coll) {
55 result[i++] = index.intValue();
56 }
57 return result;
58 }
59
60 @Benchmark
61 public int[] testBitSet() {
62 final BitSet toRemove = new BitSet();
63 int found = 0;
64 for (int i = 0; i < numberOfElementsToCompute; i++) {
65 toRemove.set(found++);
66 }
67 return extractIndices(toRemove);
68 }
69
70 @Benchmark
71 public int[] testHashSet() {
72 final HashSet<Integer> toRemove = new HashSet<>();
73 int found = 0;
74 for (int i = 0; i < numberOfElementsToCompute; i++) {
75 toRemove.add(found++);
76 }
77 return extractIndices(toRemove);
78 }
79
80 @Benchmark
81 public int[] timeBitSetRemoveAll() {
82 final BitSet toRemove = new BitSet();
83 final int[] array = new int[100];
84 toRemove.set(10, 20);
85 return (int[]) ArrayUtils.removeAll(array, toRemove);
86 }
87
88 @Benchmark
89 public int[] timeExtractRemoveAll() {
90 final BitSet toRemove = new BitSet();
91 final int[] array = new int[100];
92 toRemove.set(10, 20);
93 final int[] extractIndices = extractIndices(toRemove);
94 return (int[]) ArrayUtils.removeAll((Object) array, extractIndices);
95 }
96 }