如何加速输出字符串的缓冲
本文关键字:输出 字符串 缓冲 加速 何加速 | 更新日期: 2023-09-27 18:05:57
这段代码乘以输出一个~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();
}
}
}
}
String方法耗时2.2985349秒直接法取0.07191s
这是在3.5GHz CPU和5Gb RAM上。
我很失望,简单地缓冲字符串中的输出是如此昂贵!
在我的实际程序中,我需要延迟输出,直到字符串组装完成。有更快的方法吗?
是的,使用StringBuilder
来组装您的字符串。
有关性能提升的深入解释,请参阅"使用StringBuilder类"-但基本上因为字符串是不可变的,所以当您连接时将创建一个新字符串,这是非常昂贵的。