Performance String.+ vs String.Format

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.

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值