C# 是否优化字符串文字的连接? [英] Does C# optimize the concatenation of string literals?

查看:33
本文介绍了C# 是否优化字符串文字的连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,编译器知道翻译吗

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):

每当一个表达式满足上面列出的要求,表达式在编译时.这是真的,即使表达式是一个子表达式更大的表达式包含非常量结构.

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.

(上面列出的要求"包括应用于两个常量表达式的 + 运算符.)

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

另见这个问题.

这篇关于C# 是否优化字符串文字的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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