A Better StringBuilder
Join the DZone community and get the full member experience.
Join For FreeAlmost 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).
Strings
Data Types
Object (computer science)
Opinions expressed by DZone contributors are their own.
Trending
-
Extending Java APIs: Add Missing Features Without the Hassle
-
Decoding ChatGPT: The Concerns We All Should Be Aware Of
-
Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
-
How To Use Git Cherry-Pick to Apply Selected Commits
Comments