【问题标题】:How to accelerate buffering of output string?如何加速输出字符串的缓冲?
【发布时间】:2013-03-27 02:00:35
【问题描述】:

这段代码乘以两种输出 ~380Kb 字符串的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static string outbuff = "";
        static void Main(string[] args)
        {
            {
                Stopwatch exectime = new Stopwatch();
                System.IO.StreamWriter file;
                exectime.Reset(); exectime.Start();
                file = new System.IO.StreamWriter("output.html");
                for (int i = 0; i < 18000; i++)
                {
                    outbuff += "444444444, 5555555555\n";
                }
                string fin = "\nString method took " + exectime.Elapsed.TotalSeconds + "s";
                file.WriteLine(outbuff);
                Console.WriteLine(fin);
                file.WriteLine(fin);
                file.Close();
            }
            {
                Stopwatch exectime = new Stopwatch();
                System.IO.StreamWriter file;

                exectime.Reset(); exectime.Start();
                file = new System.IO.StreamWriter("output2.html");
                for (int i = 0; i < 18000; i++)
                {
                    file.Write("444444444, 5555555555\n");
                }
                string fin = "\nDirect method took " + exectime.Elapsed.TotalSeconds + "s";
                Console.WriteLine(fin);
                file.WriteLine(fin);
                file.Close();
            }
        }
    }
}

字符串方法耗时 2.2985349s 直接法耗时0.07191s

这是在具有 5Gb RAM 的 3.5GHz CPU 上。

我很失望,简单地将输出缓冲在一个字符串中是如此昂贵!

在我的实际程序中,我需要延迟输出直到字符串被组装。有更快的方法吗?

【问题讨论】:

    标签: c# windows-7 visual-studio-2012


    【解决方案1】:

    是的,请改用StringBuilder 来组装您的字符串。

    有关性能提升的深入解释,请参阅"Using the StringBuilder Class" - 但基本上因为字符串是不可变的,所以在连接时会创建一个新字符串,这非常昂贵。

    【讨论】:

    • "StringBuilder 方法耗时 0.0018911s" 已排序!谢谢,BG。虽然我必须说(称我为老式),但我认为这种优化是编译器的工作......
    • @ChrisJJ 编译器可以做很多有趣的优化,但它有局限性。它归结为String 类的实现方式,它是作为静态缓冲区完成的。更改字符串通常需要一个新的缓冲区。 StringBuilder 类可以预分配缓冲区、动态调整缓冲区大小等以更快更快地进行字符串操作。
    • "更改字符串通常需要一个新的缓冲区。"多么可怕的 20thC :) 感谢您的解释。
    • +1。 @ChrisJJ,不确定您试图以哪种方式开玩笑说无法修改“字符串”值...但是如果您曾经尝试编写正确的多线程代码来处理潜在的可变字符串,您可能会认为不可变字符串真的是未来的方式。
    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多