No livro “Effective Java” do Joshua Block, na página 155, ele fala sobre a performance na concatenação de Strings, veja esse exemplo :
// Inappropriate use of string concatenation - Performs horribly !
public String statement() {
String s = "";
for (int i = 0; i < numItems(); i++)
s += lineForItem(i); // String concatenation
return s;
Daí ele fala para utilizar a classe StringBuffer e até comentou que na máquina dele utilizando o StringBuffer foi 90 vezes mais rápido.
public String statement() {
StringBuffer s = new StringBuffer(numItems() * LINE_WIDTH);
for (int i = 0; i < numItems(); i++)
s.append(lineForItem(i)); // String concatenation
return s.toString();
Nesse caso ele utilizou o JDK 1.3.
Eu estive vendo a classe StringBuffer na documentação do JDK 1.4.0 e lá diz :
String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:
x = “a” + 4 + “c” is compiled to the equivalent of:
x = new StringBuffer().append(“a”).append(4).append(“c”).toString()
which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.
Estive vendo a documentação do JDK 1.3 e é a mesma coisa, será que a performance foi melhor porque ele alocou o StringBuffer com numItems() * LINE_WIDTH ?
O estranho é que ele nem comentou que a contatenação de Strings é implementada como um StringBuffer pelo compilador.
Ainda vou fazer o teste medindo o tempo com um StringBuffer com a alocação default e uma alocação definida pelo Joshua Block.
O que vocês acham ?