St.Antario
St.Antario

Reputation: 27425

Exclude method invocation from performance measurement

I'm trying to write a benchmark in JMH to measure a performance of our customized collection.

I mean the performance of putting an object into it. The thing is on each iteration I want to generate an object to put, but I want to exclude the generation from the benchmark result itself.

Here is how it would look like:

@Benchmark
public void m(){
    Collection<Object> c = create();
    Object o = createObject();
    // I want to measure performance of the following line only
    c.add(o);
}

public Collection<Object> create(){
    //return the instance of the collection
}

public Object createObject(){
    //return some object
}

I know about the @Setup annotation, but it is only invoked when benchmark is started. So its not exactly what I want.

Upvotes: 1

Views: 54

Answers (1)

GhostCat
GhostCat

Reputation: 140553

You could create those objects within a setup method, and for example store them in a pre-built array.

Then providing new objects boils down to an array access and index increase operation. I am pretty sure that you will not find a way to do that with less effort.

In other words: if you do not want to benchmark object creation, then the only other alternative is to create them upfront and somehow remember them for later use. And if @Setup isn't what you are looking for; simply use some static array that gets filled when your class gets loaded.

Upvotes: 1

Related Questions