Given the 2 toString()
implementations below, which one is preferred:
public String toString(){
return \"{a:\"+ a + \", b:\" + b + \", c: \"
In most cases, you won't see an actual difference between the two approaches, but it's easy to construct a worst case scenario like this one:
public class Main
{
public static void main(String[] args)
{
long now = System.currentTimeMillis();
slow();
System.out.println("slow elapsed " + (System.currentTimeMillis() - now) + " ms");
now = System.currentTimeMillis();
fast();
System.out.println("fast elapsed " + (System.currentTimeMillis() - now) + " ms");
}
private static void fast()
{
StringBuilder s = new StringBuilder();
for(int i=0;i<100000;i++)
s.append("*");
}
private static void slow()
{
String s = "";
for(int i=0;i<100000;i++)
s+="*";
}
}
The output is:
slow elapsed 11741 ms
fast elapsed 7 ms
The problem is that to += append to a string reconstructs a new string, so it costs something linear to the length of your strings (sum of both).
So - to your question:
The second approach would be faster, but it's less readable and harder to maintain. As I said, in your specific case you would probably not see the difference.