如何加速输出字符串的缓冲?

Chr*_*sJJ 0 c# windows-7 visual-studio-2012

此代码计时输出~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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

字符串方法取2.2985349s直接方法取0.07191s

这是一个3.5GHz的CPU,带有5Gb RAM.

我很失望只是简单地缓冲字符串中的输出是如此昂贵!

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

Bro*_*ass 7

是的,使用a StringBuilder来汇编你的字符串.

有关性能提升的深入解释,请参阅"使用StringBuilder类" - 但主要是因为字符串是不可变的,所以在连接时会创建一个新字符串,这非常昂贵.