# Use StringBuilder::append
# Description
Replaces the infix operator +
over String
concatenations with at least three operands by StringBuilder::append
. When possible, unwraps the parenthesized expressions.
# Benefits
Improves the performance of the String concatenations.
# Tags
# Code Changes
# Concatenating strings in infix expressions
Pre
String value = "prefix" + "value" + "suffix";
Post
String value = new StringBuilder().append("prefix")
.append("value")
.append("suffix")
.toString();
# Resolving types of arithmetic expressions
Pre
String value = "prefix" + 2 * 3 + ("value" + 2 + 3) + (4 + 5) + "suffix";
Post
String value = new StringBuilder().append("prefix")
.append(2*3)
.append("value")
.append(2)
.append(3)
.append(4 + 5)
.append("suffix")
.toString();
# Resolving types of numeric literals
Pre
String value = 5 + " (five) = " + 3 + " (three) + " + 2 + " (two).";
Post
String value = new StringBuilder().append(5)
.append(" (five) = ")
.append(3)
.append(" (three) + ")
.append(2)
.append(" (two).")
.toString();
# Limitations
If at least two of the first operands of the expression are numeric additions then the expression is evaluated by Java as numeric expression rather than String expression. Therefore, the transformation is not performed. E.g.:
Pre
String value = 2 + 3 + "";
You Want To Have Those Changes Done Automatically?
The automatic application of this rule is supported in the following jSparrow version: