1
\$\begingroup\$

I am learning to write micro bench marks for Java methods. I read that while writing methods for bench marking we should be careful of writing code which compiler/JVM can optimize.

I have writeen my first bench mark for stack. Just by looking at my code it looks like a lot of code being repeated hence i doubt whether this code can be optimized by JVM. Please have a look at the code and share your thoughts?

Basically I want to test for multiple push and pop calls.

 @Benchmark
@BenchmarkMode(Mode.All)
@OutputTimeUnit(TimeUnit.SECONDS)
public void benchMark_Array(Blackhole blackhole) {
    StringBuilder stringBuilder = new StringBuilder();

    Stack<String> stack = new StackArrayImpl<>();
    stack.push("String 11");
    stack.push("String 12");
    stack.push("String 13");
    stack.push("String 14");
    stack.push("String 15");
    stack.push("String 16");
    stack.push("String 17");
    stack.push("String 18");
    stack.push("String 19");
    stack.push("String 2");
    stack.push("String 1");

    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());
    stringBuilder.append(stack.pop());

    blackhole.consume(stringBuilder.toString());
}
\$\endgroup\$
  • \$\begingroup\$ Could you clarify what you want to measure exactly? Is it the performance of push with a varying number of elements already in the stack? \$\endgroup\$ – Tunaki Jun 3 '16 at 13:05
  • \$\begingroup\$ Also, what is StackArrayImpl? Could you post its code if it is a custom class? \$\endgroup\$ – Tunaki Jun 3 '16 at 17:58
  • \$\begingroup\$ Yes, i want to measure the throughput of the operation. I don't have any issue with my implementation. I want the code for bench marking to be reviewed for optimizations which JVM might apply. StackArrayImpl is the implementation of Stack using Array. \$\endgroup\$ – Balkrishan Nagpal Jun 5 '16 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.