gpt4 book ai didi

c# - 优化代码,使其执行得更快

转载 作者:行者123 更新时间:2023-11-30 13:07:10 27 4
gpt4 key购买 nike

如何优化以下代码以使其执行得更快?

static void Main(string[] args) 
{
String a = "Hello ";
String b = " World! ";
for (int i=0; i<20000; i++)
{
a = a + b;
}
Console.WriteLine(a);
}

最佳答案

来自StringBuilder文档:

Performance Considerations

The Concat and AppendFormat methods both concatenate new data to an existing String or StringBuilder object. 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 end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.

The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

static void Main(string[] args) {
String a = "Hello ";
String b = " World! ";
StringBuilder result = new StringBuilder(a.Length + b.Length * 20000);
result.Append(a);
for (int i=0; i<20000; i++) {
result.Append(b);
}
Console.WriteLine(result.ToString());
}

关于c# - 优化代码,使其执行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1290621/

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