Skip to content

Instantly share code, notes, and snippets.

@jponge
Created December 16, 2015 10:18
Show Gist options
  • Save jponge/82aa11193cc22f224ca7 to your computer and use it in GitHub Desktop.
Save jponge/82aa11193cc22f224ca7 to your computer and use it in GitHub Desktop.
package org.typeunsafe;
import org.openjdk.jmh.annotations.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class MyBenchmark {
private int index = 0;
private Object[] listObjects;
private Object[] mixedObjects;
@Setup
public void prepare() {
listObjects = new Object[]{
new ArrayList<Object>() {
{
add(1);
add(2);
add(3);
}
},
new LinkedList<Object>() {
{
add("Plop");
add("Da Plop");
}
},
new ArrayList<Object>(),
new LinkedList<Object>() {
{
add("Plop");
}
},
new ArrayList<Object>() {
{
add(100);
add(200);
add(300);
}
},
};
mixedObjects = new Object[]{
new ArrayList<Object>() {
{
add(1);
add(2);
add(3);
}
},
new LinkedList<Object>() {
{
add("Plop");
add("Da Plop");
}
},
new ArrayList<Object>(),
"That's a string",
69
};
}
private int nextIndex() {
return (index + 1) % listObjects.length;
}
@Benchmark
public int if_only_lists() {
Object obj = listObjects[nextIndex()];
if (obj instanceof List) {
return ((List) obj).size();
}
return -1;
}
@Benchmark
public int if_mixed_objects() {
Object obj = mixedObjects[nextIndex()];
if (obj instanceof List) {
return ((List) obj).size();
}
return -1;
}
@Benchmark
public int trycatch_only_lists() {
try {
return ((List) listObjects[nextIndex()]).size();
} catch (ClassCastException e) {
return -1;
}
}
@Benchmark
public int trycatch_mixed_objects() {
try {
return ((List) mixedObjects[nextIndex()]).size();
} catch (ClassCastException e) {
return -1;
}
}
}
Benchmark Mode Cnt Score Error Units
MyBenchmark.if_mixed_objects thrpt 20 111741.999 ± 1463.380 ops/ms
MyBenchmark.if_only_lists thrpt 20 114264.985 ± 2083.101 ops/ms
MyBenchmark.trycatch_mixed_objects thrpt 20 113566.186 ± 1157.158 ops/ms
MyBenchmark.trycatch_only_lists thrpt 20 118021.702 ± 1691.867 ops/ms
@yloiseau
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment