我有一个短裤数组(short []),我需要写出一个文件。最快的方法是什么?
答案 0 :(得分:11)
使用BinaryWriter
static void WriteShorts(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (short value in values)
{
bw.Write(value);
}
}
}
}
答案 1 :(得分:2)
根据Jon B的回答,如果您的文件包含任何其他数据,您可能希望在数据前面加上值的数量。
即:
static void WriteShorts(short[] values, string path)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
// Write the number of items
bw.Write(values.Length);
foreach (short value in values)
{
bw.Write(value);
}
}
}
}
答案 2 :(得分:1)
BinaryFormatter 实际上,与基本类型数组(obj.GetType()。IsPrimitive)一起使用时读取和写入的强度大约快10倍,即不适用于十进制和字符串(不是原始的),当然不适用于任何其他结构或类,而是非常慢。
[Test]
public void TestShortArray()
{
var n = 100000000;
var input = new short[n];
var r = new Random();
for (var i = 0; i < n; i++) input[i] = (short)r.Next();
var bf = new BinaryFormatter();
var sw = new Stopwatch();
using (var ms = new MemoryStream())
{
sw.Start();
bf.Serialize(ms, input);
sw.Stop();
Console.WriteLine("BinaryFormatter serialize: " +
sw.ElapsedMilliseconds + " ms, " + ms.ToArray().Length + " bytes");
sw.Reset();
ms.Seek(0, SeekOrigin.Begin);
sw.Start();
var output = (short[])bf.Deserialize(ms);
sw.Stop();
Console.WriteLine("BinaryFormatter deserialize: " +
sw.ElapsedMilliseconds + " ms, " + ms.ToArray().Length + " bytes");
Assert.AreEqual(input, output);
}
sw.Reset();
using (var ms = new MemoryStream())
{
var bw = new BinaryWriter(ms, Encoding.UTF8, true);
sw.Start();
bw.Write(input.Length);
for (var i = 0; i < input.Length; i++) bw.Write(input[i]);
sw.Stop();
Console.WriteLine("BinaryWriter serialize: " +
sw.ElapsedMilliseconds + " ms, " + ms.ToArray().Length + " bytes");
sw.Reset();
ms.Seek(0, SeekOrigin.Begin);
var br = new BinaryReader(ms, Encoding.UTF8, true);
sw.Start();
var length = br.ReadInt32();
var output = new short[length];
for (var i = 0; i < length; i++) output[i] = br.ReadInt16();
sw.Stop();
Console.WriteLine("BinaryReader deserialize: " +
sw.ElapsedMilliseconds + " ms, " + ms.ToArray().Length + " bytes");
Assert.AreEqual(input, output);
}
}
输出:
BinaryFormatter serialize: 175 ms, 200000028 bytes
BinaryFormatter deserialize: 79 ms, 200000028 bytes
BinaryWriter serialize: 1499 ms, 200000004 bytes
BinaryReader deserialize: 1599 ms, 200000004 bytes
因此,只要有原始类型的数组或数组数组但不是多维数组(!),就使用BinaryFormatter。如果你的数据类型是例如Point3(double),你应该填充double []并将其序列化。仅对复杂/混合类型,字符串,小数和奇异值使用BinaryWriter。
当处理byte []时,BinaryFormatter和BinaryWriter同样具有高性能(并且速度非常快)。如果您能够以有效的方式将类型转换为字节数组,则可以通过这种方式获得更快的性能。