Skip to content

Instantly share code, notes, and snippets.

@twillouer
Created November 15, 2014 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twillouer/ac13eb1dadc8a270f821 to your computer and use it in GitHub Desktop.
Save twillouer/ac13eb1dadc8a270f821 to your computer and use it in GitHub Desktop.
Benchmarking of toArray
@State(Scope.Benchmark)
public class ToArrayBench {
ArrayList<Byte> list;
@Setup
public void setup() throws Throwable
{
list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add((byte) i);
}
}
@Benchmark
public void zero_sized_array()
{
list.toArray(new Byte[0]);
}
@Benchmark
public void simple_toArray()
{
list.toArray();
}
@Benchmark
public void sized_array_from_list()
{
list.toArray(new Byte[list.size()]);
}
@Benchmark
public void sized_array_fixed_size()
{
list.toArray(new Byte[100]);
}
@Benchmark
public void defensive_copy()
{
new ArrayList<>(list);
}
public static void main(String[] args) throws RunnerException, IOException
{
Options opt = new OptionsBuilder().include(".*" + ToArrayBench.class.getSimpleName() + ".*")
.warmupIterations(20)
.warmupTime(TimeValue.seconds(1))
.measurementIterations(20)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
// .addProfiler(LinuxPerfProfiler.class)
.build();
new Runner(opt).run();
}
}
@shipilev
Copy link

Routinely, I will chew on people who can't use perfasm profiler, but this is not your fault it wasn't helping here. ;) Only in JMH 1.5+ (released yesterday) perfasm can decode the VM stubs, and VM stubs are the crucial piece of info to untangle this. See: http://cr.openjdk.java.net/~shade/scratch/ToArrayBench.java

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