Java String concatenation performance concern.

/************Don't do this***********/
String[] strings = new String[]{"one", "two", "three", "four", "five"};

String result = null;
for(String string : strings) {
    result = result + string;
}
/************Because it ends up in this********/
String[] strings = new String[]{"one", "two", "three", "four", "five"};

String result = null;
for(String string : strings) {
    result = new StringBuilder(result).append(string).toString();
}


// Instead do this
String[] strings = new String[]{"one", "two", "three", "four", "five"};

StringBuilder temp  = new StringBuilder();
for(String string : strings) {
    temp.append(string);
}
String result = temp.toString();

See reference here for more.

Post tagged with: java