String prefix = "";
for (String serverId : serverIds) {
sb.append(prefix);
prefix = ",";
sb.append(serverId);
}
The following code runs faster than the above code . the "," prefix object does unnecessary object creation on every iteration . The above code takes 86324 nano seconds,while mine takes only 68165 nano seconds.
List<String> l = Arrays.asList("SURESH1","SURESH2","SURESH4","SURESH5");
StringBuffer l1 = new StringBuffer();
int sz = l.size();
int i=0; long t =
System.nanoTime();
for (String s : l)
{
l1.append(s);
if ( i != sz-1)
l1.append(","); i++;
}
}
long t2 = System.nanoTime();
System.out.println ((t2-t)); System.out.println(l1);
// The time taken for the above code is 68165 nano seconds
SURESH1,SURESH2,SURESH4,SURESH5
kindly let me know which one is better in ur view.