字符串连接使用常量 - 性能 [英] String Concat using constants - performance

查看:137
本文介绍了字符串连接使用常量 - 性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串常量:

Assume I have the following string constants:

const string constString1 = "Const String 1";
const string constString2 = "Const String 2";
const string constString3 = "Const String 3";
const string constString4 = "Const String 4";

现在我可以追加字符串有两种方式:
选项1:

Now I can append the strings in two ways: Option1:

string resultString = constString1 + constString2 + constString3 + constString4;



选项2:

Option2:

string resultString = string.Format("{0}{1}{2}{3}",constString1,constString2,constString3,constString4);



在内部的String.Format使用StringBuilder.AppendFormat。现在,鉴于我追加常量字符串,其中的选项(选项1或选项2)相对于性能和/或内存更好?

Internally string.Format uses StringBuilder.AppendFormat. Now given the fact that I am appending constant strings, which of the options (option1 or option 2) is better with respect to performance and/or memory?

推荐答案

第一个将被编译器进行的(至少在微软的C#编译器)(以同样的方式,编译器确实1 + 2),第二个,必须在运行时完成。如此明确第一个是快

The first one will be done by the compiler (at least the Microsoft C# Compiler) (in the same way that the compiler does 1+2), the second one must be done at runtime. So clearly the first one is faster.

作为一个额外的好处,在第一个字符串被内化,在第二个是不

As an added benefit, in the first one the string is internalized, in the second one it isn't.

和的String.Format是相当缓慢:-)(阅读
http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/formatting-strings.aspx )。 NOT慢足以成为一个问题,除非所有程序完成所有的一天是格式字符串(他们数以百万计,而不是TENS)。然后,你可以大概更快追加 ING他们一个的StringBuilder

And String.Format is quite slow :-) (read this http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/formatting-strings.aspx). NOT "slow enough to be a problem", UNLESS all your program do all the day is format strings (MILLIONS of them, not TENS). Then you could probably to it faster Appending them to a StringBuilder.

这篇关于字符串连接使用常量 - 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆