为什么String.Concat不优化StringBuilder.Append?Concat、String、Append、StringBuilder

2023-09-02 10:30:22 作者:迩是我寻觅已久的温柔。

OK,这样的常量字符串EX pressions级联由编译器优化成一个字符串。太好了。

OK, so concatenations of constant string expressions are optimized by the compiler into one string. Great.

现在有在运行时才知道字符串字符串连接,为什么编译器不会优化字符串连接的环路,并说10多串用的串联 StringBuilder.Append 代替?我的意思是,这是可能的,对不对?实例化一个的StringBuilder ,并采取每一个串联并把它变成一个追加()电话。

Now with string concatenation of strings only known at runtime, why does the compiler not optimize string concatenation in loops and concatenations of say more than 10 strings to use StringBuilder.Append instead? I mean, it's possible, right? Instantiate a StringBuilder and take each concatenation and turn it into an Append() call.

时有什么理由这样的应该或可以的不可以进行优化?我在想什么?

Is there any reason why this should or could not be optimized? What am I missing?

推荐答案

该肯定的答案将来自编译器的设计团队。但是,让我来刺在这里...

The definite answer will have to come from the compiler design team. But let me take a stab here...

如果你的问题是,为什么编译器不会把这样的:

If your question is, why the compiler doesn't turn this:

string s = "";
for( int i = 0; i < 100; i ++ )
    s = string.Concat( s, i.ToString() );

这个:

StringBuilder sb = new StringBuilder();
for( int i = 0; i < 100; i++ )
    sb.Append( i.ToString() );
string s = sb.ToString();

最有可能的答案是,这是不是一种优化。这是code,介绍基于知识和意图,开发商有了新的结构重写 - 不是编译器。

The most likely answer is that this is not an optimization. This is a rewrite of the code that introduces new constructs based on knowledge and intent that the developer has - not the compiler.

此类型的变化将需要编译器有BCL比是合适的更多的知识。如果明天一定更优化串组件服务可用什么?如果编译器使用?

This type of change would require the compiler to have more knowledge of the BCL than is appropriate. What if tomorrow, some more optimal string assembly service becomes available? Should the compiler use that?

如果你的循环条件比较复杂,应该编译器试图执行一些静态分析来决定这种重写的结果是否仍然是功能上等同?在许多方面,这会像解决停机问题。

What if your loop conditions were more complicated, should the compiler attempt to perform some static analysis to decide whether the result of such a rewrite would still be functionally equivalent? In many ways, this would be like solving the halting problem.

最后,我不知道,在所有情况下,这将导致更快的表演code。有一个成本实例化一个的StringBuilder 和调整其内部缓冲区文本被追加。事实上,追加的成本强烈依赖于字符串的大小被连接在一起,有多少,pressure看起来什么内存等。这些都是编译器不能predict提前。

Finally, I'm not sure that in all cases this would result in faster performing code. There is a cost to instantiating a StringBuilder and resizing its internal buffer as text is appended. In fact, the cost of appending is strongly tied to the size of the string being concatenated, how many there are, what memory pressure looks like. These are things that the compiler cannot predict in advance.

这是你的工作,作为一个开发人员编写运行良好的code 的编译器可以使某些的安全的,invariant- preserving优化不仅帮助。不重写你的code你。

It's your job as a developer to write well-performing code. The compiler can only help by making certain safe, invariant-preserving optimizations. Not rewriting your code for you.