So I've been looking back on code I've written almost a year and a half ago trying to fix it and I found this function that has got me confused. I searched for a method to do the same thing and found a pretty decent function and I'm curious at what would be better.
Function A:
public static String listToString(List<String> list){
StringBuilder sb = new StringBuilder();
if (list != null && list.size() > 1){
sb.append(list.get(0));
for (int i = 1; i < list.size(); i++){
sb.append(", " + list.get(i));
}
}else if(list != null && (list.size() == 1)){
sb.append(list.get(0));
}
return sb.toString();
}
Function B:
public static String listToString(List<String> list) {
String str = "";
for (String s : list) {
str += s + ", ";
}
return str;
}
Now I wrote Function A within my first couple months of learning Java so I probably didn't know best though is there any reason I should stick to this method?
Stringconcatenation in loops can't be optimised by the JVM at runtime and is woefully inefficient (creating lots of short lived objects that need to be GC). Function A is in the right direction, exceptsb.append(", " + list.get(i));defeats the purpose and should besb.append(", ").append(list.get(i));StringUtils.join. Don't re-invent wheels.str3 = str1 + str2requires copying all of the chars instr1andstr2into thechar[]thatstr3uses (twice, actually: once for the temporaryStringBuilderand once for the newStringit produces). If you dostr += foo, that means that each time around, the previousstrchars will be copied to create the newstr. The original str's chars are copied N times, the first loop's str chars are copied N-1 times, etc. It's an N^2 operation, which is worse than the object allocation.