Why is String.Concat not optimized to StringBuilder.Append?

后端 未结 8 1198
小鲜肉
小鲜肉 2020-12-05 07:39

I found concatenations of constant string expressions are optimized by the compiler into one string.

Now with string concatenation of strings only known at run-time,

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 07:58

    A String is an immutable type, hence using concatenating the string is slower than using StringBuilder.Append.

    Edit: To clarify my point a bit more, when you talk about why is String.Concat not optimized to StringBuilder.Append, a StringBuilder class has completely different semantics to the immutable type of String. Why should you expect the compiler to optimize that as they are clearly two different things? Furthermore, a StringBuilder is a mutable type that can change its length dynamically, why should a compiler optimize an immutable type to a mutable type? That is the design and semantics ingrained into the ECMA spec for the .NET Framework, regardless of the language.

    It's a bit like asking the compiler (and perhaps expecting too much) to compile a char and optimize it into a int because the int works on 32 bits instead of 8 bits and would be deemed faster!

提交回复
热议问题