Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Better StringBuilder

DZone's Guide to

A Better StringBuilder

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

Almost noone likes using string "+" for complex text creation. Long chains of .append with StringBuilder also look ugly. So, often one will see something like the following:
StringBuilder builder = new StringBuilder();
builder.append("Hello, world\n")
if (name != null) {
    builder.append(String.format("My name is %s\n", name));
} else {
    builder.append(String.format("Please email me at %s\n", email);
}
doUse(builder.toString();
But does anyone think that this code is almost as bad in performance as str += name? String.format call creates a new StringBuilder, new Formater, then creates String out of this thing and then appends String to your builder. Consider a better way:
Formatter formatter = new Formatter();
formatter.format("Hello, world\n");
if (name != null) {
    formatter.format("My name is %s\n", name);
} else {
    formatter.format("Please email me at %s\n", email);
}
doUse(formatter.toString();
This code has less boilerplate and creates less objects. The only thing you should watch for is if in formatter.format(str) str contains '%' character. But you can always use formatter.format("%s", str) or formatter.out().append(str).

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}