He encontrado que esto artical y realizado esta prueba:
public static void main(String[] args) {
String s1 = generateString();
String s2 = generateString();
String s3 = generateString();
String s4 = generateString();
String s5 = generateString();
String s6 = generateString();
long e = System.currentTimeMillis();
for(int i=0;i<10000000;i++){
//StringBuilder > concat> plus >StringBuffer >plusEqual(">"means faster than)
//concatPlus(s1 , s2 , s3 , s4 , s5 , s6);//4204ms
//concatBuilder(s1 , s2 , s3 , s4 , s5 , s6);//2562ms
//concatBuffer(s1 , s2 , s3 , s4 , s5 , s6);//4610ms
//concatPlusEqual(s1 , s2 , s3 , s4 , s5 , s6);//9843ms
//concatConcat(s1 , s2 , s3 , s4 , s5 , s6);//3036ms
}
System.out.println(System.currentTimeMillis()-e);
}
public static String concatPlusEqual(String s1, String s2, String s3, String s4,
String s5, String s6) {
String result = "";
result += s1;
result += s2;
result += s3;
result += s4;
result += s5;
result += s6;
return result;
}
public static String concatConcat(String s1, String s2, String s3, String s4,
String s5, String s6) {
String result = new String();
result.concat(s1);
result.concat(s2);
result.concat(s3);
result.concat(s4);
result.concat(s5);
result.concat(s6);
return result;
}
public static String concatBuffer(String s1, String s2, String s3, String s4,
String s5, String s6) {
return new StringBuffer(s1.length() + s2.length() + s3.length()
+ s4.length() + s5.length() + s6.length()).append(s1)
.append(s2).append(s3).append(s4).append(s5).append(s6)
.toString();
}
public static String concatBuilder(String s1, String s2, String s3, String s4,
String s5, String s6) {
return new StringBuilder(s1.length() + s2.length() + s3.length()
+ s4.length() + s5.length() + s6.length()).append(s1)
.append(s2).append(s3).append(s4).append(s5).append(s6)
.toString();
}
public static String concatPlus(String s1,String s2,String s3,String s4,String s5,String s6) {
return s1 + s2 + s3 + s4 + s5 + s6;
}
public static String generateString()
{
Random rng = new Random();
int length = 10;
String characters ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
Parece que StringBuilder
es más rápida y +=
es más lento. ¡Solo como referencia!
mira esto http://stackoverflow.com/questions/47605/java-string-concatenation –