Skip to content

Instantly share code, notes, and snippets.

@apangin
Last active August 29, 2015 14:22
Show Gist options
  • Save apangin/b701eb2c4cc128cbdc56 to your computer and use it in GitHub Desktop.
Save apangin/b701eb2c4cc128cbdc56 to your computer and use it in GitHub Desktop.
Capacity field vs. array length
package bench;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
@State(Scope.Benchmark)
@Threads(4)
public class Queue {
private static final Unsafe unsafe = getUnsafe();
private static final long base = unsafe.arrayBaseOffset(Object[].class);
private static final int scale = unsafe.arrayIndexScale(Object[].class);
private Object[] buffer;
private int capacity;
@Param({"0", "9"})
private volatile int index;
@Setup
public void setup() {
buffer = new Object[10];
capacity = buffer.length;
}
@Benchmark
public void arrayLength() {
int index = this.index;
if (index < 0 || index >= buffer.length) {
throw new ArrayIndexOutOfBoundsException();
}
unsafe.putObjectVolatile(buffer, base + index * scale, "123");
}
@Benchmark
public void capacityField() {
int index = this.index;
if (index < 0 || index >= capacity) {
throw new ArrayIndexOutOfBoundsException();
}
unsafe.putObjectVolatile(buffer, base + index * scale, "123");
}
private static Unsafe getUnsafe() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new AssertionError("Should not happen");
}
}
}
Benchmark (index) Mode Cnt Score Error Units
Queue.arrayLength 0 thrpt 5 49183,203 ± 521,193 ops/ms
Queue.arrayLength 9 thrpt 5 83877,975 ± 1261,613 ops/ms
Queue.capacityField 0 thrpt 5 84168,673 ± 898,044 ops/ms
Queue.capacityField 9 thrpt 5 83964,912 ± 1790,430 ops/ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment