有人告诉我,用StringBuilder连接字符串会更快。我已经更改了我的代码,但是我没有看到任何属性或方法来获取最终的构建字符串。

我怎样才能获得字符串?

有帮助吗?

解决方案

您可以使用 .ToString() StringBuilder 中获取 String

其他提示

当你说“将字符串与字符串构建器连接起来更快”时,只有当重复(我重复 - 重复)连接到相同的对象。

如果您只是将2个字符串连接起来并立即将结果作为 string 执行,那么使用 StringBuilder 是没有意义的。

我偶然发现了Jon Skeet对此的好评: http:// www。 yoda.arachsys.com/csharp/stringbuilder.html

如果您正在使用 StringBuilder ,那么要获得生成的字符串,只需要调用 ToString()(不出所料)。

使用StringBuilder完成处理后,使用ToString方法返回最终结果。

来自MSDN:

using System;
using System.Text;

public sealed class App 
{
    static void Main() 
    {
        // Create a StringBuilder that expects to hold 50 characters.
        // Initialize the StringBuilder with "ABC".
        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
    }
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK

我只想抛弃它可能不一定更快,它肯定会有更好的内存占用。这是因为字符串在.NET中是不可变的,每次更改字符串时都会创建一个新字符串。

关于它更快/更好的记忆:

我用Java研究了这个问题,我认为.NET会很聪明。

String的实现非常令人印象深刻。

String对象跟踪“length”和“共享” (独立于保存字符串的数组的长度)

类似

String a = "abc" + "def" + "ghi";

可以(通过编译器/运行时)实现为:

 - Extend the array holding "abc" by 6 additional spaces.
 - Copy def in right after abc 
 - copy ghi in after def. 
 - give a pointer to the "abc" string to a 
 - leave abc's length at 3, set a's length to 9
 - set the shared flag in both.

由于大多数字符串都是短命的,因此在许多情况下这会产生一些非常有效的代码。 它绝对没有效率的情况是你在循环中添加一个字符串,或者你的代码是这样的:

a = "abc";
a = a + "def";
a += "ghi";

在这种情况下,使用StringBuilder构造要好得多。

我的观点是,无论何时优化,都应该小心,除非你绝对确定你知道自己在做什么,并且你绝对确定它是必要的,并且你测试以确保优化的代码使用例通过,只需以最易读的方式对其进行编码,不要试图超越编译器。

在我查看字符串源代码之前,我浪费了3天的时间搞乱字符串,缓存/重用字符串构建器和测试速度,并且发现编译器已经比我的用例更好地完成了它。然后我不得不解释我怎么不真正知道我在做什么,我只想到我做了......

连接速度并不快 - 正如smaclell指出的那样,问题是不可变的字符串强制额外分配和重新复制现有数据。

" A&QUOT + QUOT; B&QUOT + QUOT; C"使用字符串生成器并不是更快,但是当concat的#变得更大时,带有中间字符串的重复concats变得越来越快:

x =" a&quot ;; X + =" B&QUOT ;; X + =" C&QUOT ;; ...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top