Skip to content

Instantly share code, notes, and snippets.

@itugs
Last active August 29, 2015 14:20
Show Gist options
  • Save itugs/2fb948f0a340e8ff9a29 to your computer and use it in GitHub Desktop.
Save itugs/2fb948f0a340e8ff9a29 to your computer and use it in GitHub Desktop.
SetFromListPerfTest
public class SetFromListPerfTest {
@Test
public void listToLinkedHashSetTest() throws Exception {
final List<byte[]> data = buildListData();
doTest(new Callback() {
@Override
public String name() {
return "LinkedHashSet creation";
}
@Override
public void test() {
new LinkedHashSet<byte[]>(data);
}
});
}
@Test
public void listToSetFromListTest() throws Exception {
final List<byte[]> data = buildListData();
doTest(new Callback() {
@Override
public String name() {
return "SetFromList creation";
}
@Override
public void test() {
SetFromList.of(data);
}
});
}
@Test
public void iterationLinkedHashSetTest() throws Exception {
final Set<byte[]> s = new LinkedHashSet<byte[]>(buildListData());
doTest(new Callback() {
@Override
public String name() {
return "LinkedHashSet iteration";
}
@Override
public void test() {
for (byte[] x : s) {
// skip
}
}
});
}
@Test
public void iterationSetFromListTest() throws Exception {
final Set<byte[]> s = SetFromList.of(buildListData());
doTest(new Callback() {
@Override
public String name() {
return "SetFromList iteration";
}
@Override
public void test() {
for (byte[] x : s) {
// skip
}
}
});
}
private List<byte[]> buildListData() {
List<byte[]> data = new ArrayList<byte[]>(1000000);
for (int i = 0; i < 1000000; i++) {
data.add(Integer.toString(i).getBytes());
}
return data;
}
private void doTest(Callback callback) {
List<Long> elapseds = new ArrayList<Long>(10);
for (int j = 1; j <= 10; j++) {
System.gc();
long start = System.currentTimeMillis();
callback.test();
long elapsed = System.currentTimeMillis() - start;
elapseds.add(elapsed);
System.out.println(callback.name() + " Timing : " + elapsed + " ms");
}
// remove outlier
Collections.sort(elapseds);
long sum = 0;
for (int i = 0; i < elapseds.size() - 1; i++) {
sum += elapseds.get(i);
}
System.out.println(callback.name() + " Timing avg : " + (sum / 9.0) + " ms");
}
static interface Callback {
public String name();
public void test();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment