I have a StringBuilder object where I am adding some strings like follows:
I want to know which one is better approach here, first one is this:
StringBuilder sb = new StringBuilder();
sb.Append("Hello" + "How" + "are" + "you");
and the second one is:
StringBuilder sb = new StringBuilder();
sb.Append("Hello").Append("How").Append("are").Append("you");
The first will be more efficient. The compiler will convert it to the following single call:
Measuring the performance
The best way to know which is faster is to measure it. I’ll get straight to the point: here are the results (smaller times means faster):
The number given is the number of seconds to perform the operation 100 million times in a tight loop.
Conclusions
+.Appendis faster than+. The first version is slower because of an extra call toString.Concat.In case you want to test this yourself, here’s the program I used to get the above timings: