数据长度:128188个long
BinaryWriter每次写一个long 耗时14.7828ms
StreamWriter每次写一个long 耗时44.0934 ms
FileStream每次写一个long 耗时20.5142 ms
FileStream固定chunk写入,循环操作数组,耗时13.4126 ms
byte[] chunk = new byte[datalist.Count * 8];
for (int i = 0; i < datalist.Count; i++) {
long data = datalist[i];
var bs = BitConverter.GetBytes(data);
var startIndex = i * 8;
for (int j = 0; j < 8; j++) {
chunk[startIndex + j] = bs[j];
}
}
fs.Write(chunk, 0, chunk.Length);
startTime.Stop();
lg.i($"{((float)startTime.ElapsedTicks / Stopwatch.Frequency) * 1000} ms");
fs.Flush();
fs.Close();
FileStream固定chunk写入,直接操作数组,耗时10.2729 ms
byte[] chunk = new byte[datalist.Count * 8];
for (int i = 0; i < datalist.Count; i++) {
long data = datalist[i];
var bs = BitConverter.GetBytes(data);
var startIndex = i * 8;
chunk[startIndex] = bs[0];
chunk[startIndex + 1] = bs[1];
chunk[startIndex + 2] = bs[2];
chunk[startIndex + 3] = bs[3];
chunk[startIndex + 4] = bs[4];
chunk[startIndex + 5] = bs[5];
chunk[startIndex + 6] = bs[6];
chunk[startIndex + 7] = bs[7];
}
fs.Write(chunk, 0, chunk.Length);
startTime.Stop();
lg.i($"{((float)startTime.ElapsedTicks / Stopwatch.Frequency) * 1000} ms");
fs.Flush();
fs.Close();
经排查BitConverter.GetBytes源码如下,是上面比较耗时的地方,并且每次都会创建数组文章来源:https://www.toymoban.com/news/detail-720259.html
public static unsafe byte[] GetBytes(long value)
{
byte[] bytes = new byte[8];
fixed(byte* b = bytes)
*((long*)b) = value;
return bytes;
}
可以将上面改进一下,直接将代码内联进入上面代码上, 耗时2.8165 ms文章来源地址https://www.toymoban.com/news/detail-720259.html
public static unsafe byte[] GetBytes(List<long> values) {
byte[] bytes = new byte[values.Count * sizeof(long)];
fixed (byte* ptr = bytes) {
long* longPtr = (long*)ptr;
for (int i = 0; i < values.Count; i++) {
*longPtr = values[i];
longPtr++;
}
}
return bytes;
}
var startTime = new Stopwatch();
startTime.Start();
var fs = new FileStream(saveDataPath, FileMode.Append);
byte[] chunk = GetBytes(datalist);
fs.Write(chunk, 0, chunk.Length);
startTime.Stop();
lg.i($"{((float)startTime.ElapsedTicks / Stopwatch.Frequency) * 1000} ms");
fs.Flush();
fs.Close();
到了这里,关于C# 写入文件比较的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!