StringBuffer and StringBuilder performance with JMH

The TL;DR of this post is:

  • StringBuilder is better than StringBuffer
  • StringBuilder.append(a).append(b) is better than StringBuilder.append(a+b)
  • StringBuilder.append(a).append(b) is better than StringBuilder.append(a); StringBuilder.append(b);
  • StringBuilder.append() and + are only equivalent provided that they are not nested and you don’t need to pre-sizing the builder
  • Pre-sizing the StringBuilder is like pre-sizing an ArrayList; if you know the approximate size you can reduce the garbage by specifying a capacity up-front

Most of this may be common knowledge but I hope that I can back this up with data using JMH.

http://alblue.bandlem.com/2016/04/jmh-stringbuffer-stringbuilder.html

Advertisements