请问C#优化字符串的串联?字符串

2023-09-02 10:20:20 作者:淡漠安然

例如,该编译器知道翻译

For instance, does the compiler know to translate

string s = "test " + "this " + "function";

string s = "test this function";

,从而避免与字符串连接的性能影响?

and thus avoid the performance hit with the string concatenation?

推荐答案

是的。这是由C#规范保证。这是在第7.18(在C#3.0规范的):

Yes. This is guaranteed by the C# specification. It's in section 7.18 (of the C# 3.0 spec):

每当EX pression满足   要求上述上市,   EX pression是在评估   编译时。这是即使真   EX pression是一个子-EX pression   包含较大的前pression   非恒定的构建

Whenever an expression fulfills the requirements listed above, the expression is evaluated at compile-time. This is true even if the expression is a sub-expression of a larger expression that contains non-constant constructs.

(下称上面列出的要求,包括+运算符应用到两个恒定的前pressions。)

(The "requirements listed above" including the + operator applied to two constant expressions.)

另请参阅这个问题。