There is a myth saying that we have better use String.Format. What I want to show here is that you should never use String.Format for any performance reasons. String.+ is more effective in doing string concatenation.
Conclusion
In the view of performance, String.Format is just a syntax sugar. It makes the code looks better but performs worse. I can see that many people love using String.Format. But I want to say here is that using string = string1 + string2 is much FASTER than string = String.Format(“{0}{1}”,string1,string2)
Environment
.Net Framework 2.0. Visual Studio 2005. Release Build.
Test method:
In the test, I change the length of the str1 and the number of strings that concatenates together. The length of the string being concatenate varies from 1 to 128. The number of strings that concatenates together varies from 2 to 8. All the test code are execute 50000 times and the result is the average of 8 test runs.
Test Code:
String.Format test code:
str = String.Format("{0}:{1}",str1, str1);
str = String.Format("{0}:{1}:{2}", str1, str1, str1);
………
str = String.Format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}", str1, str1, str1, str1, str1, str1, str1, str1);
String.Format test code:
str = str1 + str1;
str = str1 + str1 + str1;
……….
str = str1 + str1 + str1 + str1 + str1 + str1 + str1 + str1;
Note:
Format string “{0}:{1}” make a very small difference with “{0}{1}”. So do not use the form String.Format(“{0}{1}{2}”, string1, “?”, string2); use String.Format(“{0}?{1}”, string1, string2) instead.
Result:
Here is the two figures that shows the difference. The results may vary in different machine and different time.
Overall, we can see that String.+ out-performs String.Format in all cases. And the reduce in performance using String.Format is significant!!
In this figure, we can see that length 1 and length 8 don’t have much difference. The small decrease of String.Format line between 1 and 8 is the result of test variance.
In this figure, we can see that time increases linearly with the number of string that concatenates together for both methods.