此代码对输出 ~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 上。
我很失望,简单地将输出缓冲在一个字符串中是如此昂贵!
在我的真实程序中,我需要推迟输出,直到字符串被组装。有更快的方法吗?