The TL;DR of this post is:
StringBuilder
is better thanStringBuffer
StringBuilder.append(a).append(b)
is better thanStringBuilder.append(a+b)
StringBuilder.append(a).append(b)
is better thanStringBuilder.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 anArrayList
; 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