gpt4 book ai didi

c# - 使用 + 的字符串连接是否针对 .NET 中的 StringBuilder 实现进行了优化?

转载 作者:行者123 更新时间:2023-11-30 06:29:35 25 4
gpt4 key购买 nike

我读过多个地方,在编译程序时,Java 1.5+ String 连接优化为使用 StringBuilder。我不清楚这是标准还是许多编译器采用的常见优化。如能对此作出任何澄清,我们将不胜感激,但主要是为了引出我的第二个问题。

.NET 是否有类似的优化?我知道如果我使用 StringBuilder 这将消除任何歧义,但我个人发现 + 的简单性更易于阅读。如果 .NET 有,这是否从特定版本开始?感谢详细说明。

最佳答案

来自 MSDN:

A String object concatenation operation always creates a new object from the existing string and the new data. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is appended to the new buffer.

The performance of a concatenation operation for a String or StringBuilder object depends on the frequency of memory allocations. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation allocates memory only if the StringBuilder object buffer is too small to accommodate the new data. Use the String class if you are concatenating a fixed number of String objects. In that case, the compiler may even combine individual concatenation operations into a single operation. Use a StringBuilder object if you are concatenating an arbitrary number of strings; for example, if you're using a loop to concatenate a random number of strings of user input.

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

关于c# - 使用 + 的字符串连接是否针对 .NET 中的 StringBuilder 实现进行了优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11351160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com