gpt4 book ai didi

c# - C# 中的 StringBuilder 性能?

转载 作者:太空狗 更新时间:2023-10-29 22:10:59 24 4
gpt4 key购买 nike

我有一个 StringBuilder 对象,我在其中添加了一些字符串,如下所示:

我想知道哪种方法更好,第一种是这样的:

StringBuilder sb = new StringBuilder();
sb.Append("Hello" + "How" + "are" + "you");

第二个是:

StringBuilder sb = new StringBuilder();
sb.Append("Hello").Append("How").Append("are").Append("you");

最佳答案

在您当前的示例中,字符串文字:

"Hello" + "How" + "are" + "you"

将被编译器编译成一个常量字符串文字,因此从技术上讲它比:

sb.Append("Hello").Append("How").Append("are").Append("you");

但是,您是否使用了字符串变量:

sb.Append(s1 + s2 + s3 + s4);

那么后者会更快,因为前者可能会在 将最终字符串传递到 Append 方法之前创建一系列字符串(因为串联),而后者将避免额外的字符串创建(但权衡额外的方法调用和内部缓冲区大小调整)。

更新:为了进一步清楚,在这种只有 4 个项目被连接的确切情况下,编译器将调用 String.Concat(string, string, string, string ),它知道字符串的长度和数量会比 StringBuilder 更有效率。

关于c# - C# 中的 StringBuilder 性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938006/

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