OPT.SB
Reserve 'StringBuffer' capacity
Description
This rule flags code that does not provide an initial capacity for `StringBuffer'.
The 'StringBuffer' constructor will create a character array of a default size, typically 16. If 'StringBuffer' exceeds its capacity, 'StringBuffer' has to allocate a new character array with a larger capacity, copy the old contents into the new array, and eventually discard the old array. In many situations, you can tell in advance how large your 'StringBuffer' is likely to be. In that case, reserve enough capacity during construction and prevent the 'StringBuffer' from ever needing expansion.
Example
package OPT;
public class RSBC {
void method () {
StringBuffer buffer = new StringBuffer(); // violation
buffer.append ("hello");
}
}
Repair
Provide initial capacity for 'StringBuffer'.
public class RSBC {
void method () {
StringBuffer buffer = new StringBuffer(MAX);
buffer.append ("hello");
}
private final int MAX = 100;
}
Reference
Bulka, D. Java Performance and Scalability Volume 1: Server-Side Programming Techniques. Addison Wesley, pp. 30-31.
|