简体   繁体   English

在C#中将short []数组写入文件的最佳方法是什么?

[英]What's the best way to write a short[] array to a file in C#?

I have an array of shorts (short[]) that I need to write out to a file. 我有一个短数组(short []),我需要写出一个文件。 What's the quickest way to do this? 最快的方法是什么?

Use the BinaryWriter 使用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);
                }
            }
        }
    }

Following up on Jon B's answer, if your file contains any other data, you might want to prefix the data with the count of values. 按照Jon B的回答,如果您的文件包含任何其他数据,您可能希望在数据前面加上值的数量。

ie: 即:

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);
            }
        }
    }
}

BinaryFormatter is in fact about 10 times faster both for reads and writes when used with arrays of primitive types (obj.GetType().IsPrimitive), ie not for Decimal and String (which are not primitive) and certainly not for any other struct or class where it instead is horribly slow. 实际上,当与基本类型数组(obj.GetType()。IsPrimitive)一起使用时, BinaryFormatter的读取和写入速度要快10倍 ,即不适用于Decimal和String(不是原始的),当然也不适用于任何其他结构或相反,它的速度非常慢。

[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);
  }
}

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

So use BinaryFormatter whenever you have an array of a primitive type, or array of arrays but not multi-dim arrays (!). 因此,只要有原始类型的数组或数组数组但不是多维数组(!),就使用BinaryFormatter。 If your datatype is for instance Point3(double) you should fill up a double[] and serialize that instead. 如果你的数据类型是例如Point3(double),你应该填充double []并将其序列化。 Only use BinaryWriter for complex/mixed types, strings, decimals and singular values. 仅对复杂/混合类型,字符串,小数和奇异值使用BinaryWriter。

When dealing with byte[] then BinaryFormatter and BinaryWriter is equally performant (and very fast). 当处理byte []时,BinaryFormatter和BinaryWriter同样具有高性能(并且速度非常快)。 If you can convert your type to byte-array in an effective way you may get even faster performance this way. 如果您可以以有效的方式将类型转换为字节数组,则可以通过这种方式获得更快的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#中编写[0..100]的最佳方法是什么? - What's the best way to write [0..100] in C#? 使用C#写入Excel文件的最佳和最快的方法是什么? - What is the best and fastest way to write into Excel file using C#? 从C#中的short []数组中的数字创建逗号分隔字符串的最佳方法是什么? - What is the best way to create a Comma separated String from numbers in a short[] Array in C#? 在 C# 中创建只读数组的最佳方法是什么? - What's the best way of creating a readonly array in C#? 将项目添加到C#数组的最佳方法是什么? - What's the best way to add an item to a C# array? 在 C# 中从磁盘读取短数组的最佳方法? - Best way to read a short array from disk in C#? 允许用户在C#中浏览文件的最佳方法是什么? - What's the best way to allow a user to browse for a file in C#? C#将短数组从单声道WAV文件转换为短数组以写入立体声WAV - c# converting short array from mono wav file, to short array to write as stereo wav 在C#中从矩形数组中提取一维数组的最佳方法是什么? - What's the best way to extract a one-dimensional array from a rectangular array in C#? 在 C# 中用较小的数组复制/填充大数组的最佳方法是什么? - What's the best way to copy/fill a large array with a smaller array in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM