StringBuilder
The StringBuilder class serves as a utility to easily create strings. Strings are immutable in Apex, meaning that a String object cannot be modified once created. Any operation that appears to modify a String actually creates a new String object, which can have performance implications when dealing with heavy string manipulation.
While it doesn't possess the full capabilities of a traditional StringBuilder as seen in other languages (such as Java), it does provide a convenient way to build strings composed of many parts, as well as additional utility methods that are not available within the built-in String class.
Documentation
💾 Source Code
Implementation
- Under the hood, StringBuilder leverages the
List<>type to collect all appended objects, preventing the creation of multiple string objects during the build process - The
append()method takes in any object type and converts it to a string value - The default String representation of certain object types are influenced by the settings of the user that initiated the Apex transaction (E.g., Date Locale for Datetime)
- The
build()method callsString.join()to combine all objects within the underlying list - The behaviour of StringBuilder can be configured using various options, such as the
deduplicateproperty. The full list of options can be found documented within the source code
Demos
Basic Usage
// Initialize
StringBuilder sb = new StringBuilder();
sb.append('Hello');
sb.appendWhitespace(Whitespace.NEWLINE);
sb.append('World!');
// Output: "Hello\nWorld!"
String helloWorld = sb.build();
System.debug(helloWorld);Loops
// Initialize
StringBuilder sb = new StringBuilder();
for (Integer i = 0; i < 10; i++) {
sb.append(i);
sb.appendWhitespace(Whitespace.NEWLINE);
}
// Output: "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n"
String numbers = sb.build();
System.debug(numbers);Multiple Object Types
// Initialize
StringBuilder sb = new StringBuilder();
sb.withSeparator(' ');
sb.append('One'); // String
sb.append(true); // Boolean
sb.append(3); // Integer
// Output: "One true 3"
String multiObjectString = sb.build();
System.debug(multiObjectString);Usage Recommendations
- Building Strings within loops or when concatenating many strings together
- Creating strings with complex formatting or conditional logic, (e.g., JSON, newlines, etc.)
- Convenient for building strings in a more readable and maintainable way
- Creating strings from a combination of different object types
📝 Note
Consider StringBuilder as a convenience utility. Since Salesforce doesn't reveal the underlying implementation details of certain methods (such as String.join()), we can't assume that it's more memory or time performant than traditional string concatenation or system methods such as String.format(). However, you can always create your own benchmark tests to compare performance if desired.
Additionally, you can also try leveraging Salesforce's multiline string literals available as of the Summer '26 release (v67.0).
