I’ve heard that using StringBuilder is faster than using string concatenation, but I’m tired of wrestling with StringBuilder objects all of the time. I was recently exposed to the SLF4J logging library and I love the “just do the right thing” simplicity of its formatting when compared with String.format. Is there a library out there that would allow me to write something like:
int myInteger = 42;
MyObject myObject = new MyObject(); // Overrides toString()
String result = CoolFormatingLibrary.format("Simple way to format {} and {}",
myInteger, myObject);
Also, is there any reason (including performance but excluding fine-grained control of date and significant digit formatting) why I might want to use String.format over such a library if it does exist?
For concatenating strings one time, the old reliable
"str" + param + "other str"is perfectly fine (it’s actually converted by the compiler into aStringBuilder).StringBuilders are mainly useful if you have to keep adding things to the String, but you can’t get them all into one statement. For example, take a
forloop:This will run much slower than the equivalent StringBuilder version:
But these two are functionally equivalent:
Having said all that, my actual answer is:
Check out
java.text.MessageFormat. Sample code from the Javadocs:Output:
There is also a static
formatmethod which does not require creating aMessageFormatobject.All such libraries will boil down to string concatenation at their most basic level, so there won’t be much performance difference from one to another.