OPT.USB
Use `StringBuffer' instead of `String' for non-constant strings
Description
This rule flags code that uses `String' instead of `StringBuffer' for non-constant strings.
Although the += operator is provided by the `String' class, it is much less efficient than the `StringBuffer.append()' function. Using `StringBuffer' instead of using "+=" on `String' objects will improve performance.
Example
package OPT;
class USB {
public String foobar() {
String fruit = "apples";
fruit+= ", bananas"; // Violation
return fruit;
}
}
Repair
public String betterFoobar() {
StringBuffer fruit = new StringBuffer("apples");
fruit.append(", bananas");
return fruit.toString();
}
Reference
Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp.107 - 109
|