【发布时间】: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