Skip to content

Instantly share code, notes, and snippets.

@RossTate
Created August 19, 2020 02:23
Show Gist options
  • Save RossTate/bfbc3daad187d574b599e101684f7ca7 to your computer and use it in GitHub Desktop.
Save RossTate/bfbc3daad187d574b599e101684f7ca7 to your computer and use it in GitHub Desktop.
Microbenchmark for comparing overheads of various casting mechanisms
public class CastComparison {
final static int max = Integer.MAX_VALUE;
static class Super {
final int x;
Super(int x) { this.x = x; }
}
final static class Sub1 extends Super {
Sub1(int x) { super(x); }
}
final static class Sub2 extends Super {
Sub2(int x) { super(x); }
}
public static void main(String[] args) {
Super[] supers = new Super[1000];
Object[] finals = new Object[1000];
Object[] mids = new Object[1000];
int[][] ints = new int[1000][];
for (int i = 0; i < 1000; i++) {
finals[i] = new Sub1(i);
mids[i] = supers[i] = i%2 == 0 ? new Sub1(i) : new Sub2(i);
ints[i] = new int[] {i};
}
int sum;
long before, after;
for (int i = 0; i < 10; i++) {
sum = sumBaseline(supers);
sum += sumBaseline(supers);
before = System.currentTimeMillis();
sum += sumBaseline(supers);
after = System.currentTimeMillis();
System.out.println(sum + " " + (after - before));
sum = sumFinalCast(finals);
sum += sumFinalCast(finals);
before = System.currentTimeMillis();
sum += sumFinalCast(finals);
after = System.currentTimeMillis();
System.out.println(sum + " " + (after - before));
sum = sumMidCast(mids);
sum += sumMidCast(mids);
before = System.currentTimeMillis();
sum += sumMidCast(mids);
after = System.currentTimeMillis();
System.out.println(sum + " " + (after - before));
sum = sumArray(ints);
sum += sumArray(ints);
before = System.currentTimeMillis();
sum += sumArray(ints);
after = System.currentTimeMillis();
System.out.println(sum + " " + (after - before));
System.out.println();
}
}
public static int sumBaseline(Super[] supers) {
int sum = 0;
for (int i = 0; i < max; i++)
sum += supers[i % 1000].x;
return sum;
}
public static int sumFinalCast(Object[] finals) {
int sum = 0;
for (int i = 0; i < max; i++)
sum += ((Sub1)finals[i % 1000]).x;
return sum;
}
public static int sumMidCast(Object[] mids) {
int sum = 0;
for (int i = 0; i < max; i++)
sum += ((Super)mids[i % 1000]).x;
return sum;
}
public static int sumArray(int[][] ints) {
int sum = 0;
for (int i = 0; i < max; i++)
sum += ints[i % 1000][0];
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment