Skip to content

Instantly share code, notes, and snippets.

@AdamStelmaszczyk
Last active December 19, 2015 16:11
Is returning a static empty array faster than creating a new one?
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.infra.Blackhole;
public class MyBenchmark {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
@Benchmark
public void testStatic(Blackhole blackhole) {
blackhole.consume(EMPTY_STRING_ARRAY);
}
@Benchmark
@Fork(jvmArgs = "-XX:-EliminateAllocations")
public void testStaticEliminate(Blackhole blackhole) {
blackhole.consume(EMPTY_STRING_ARRAY);
}
@Benchmark
public void testNew(Blackhole blackhole) {
blackhole.consume(new String[0]);
}
@Benchmark
@Fork(jvmArgs = "-XX:-EliminateAllocations")
public void testNewEliminate(Blackhole blackhole) {
blackhole.consume(new String[0]);
}
@Benchmark
public void noop(Blackhole blackhole) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment