문제

If I were reading byte numbers I would do:

using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    int size = (int) stream.Length;
    BinaryReader br = new BinaryReader(stream);
    byte[] test = new byte[size];
    test = br.ReadBytes(size);
    br.Close();
}

But since I want to read Uint16, I am struck doing:

using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    int size = (int) stream.Length;
    BinaryReader br = new BinaryReader(stream);
    float[] test = new byte[size/2];
    for (int i = 0; i < size/2; ++i)
    {
         test[i] = br.ReadUInt16();
    }
    br.Close();
}

Is there a faster way to read the whole file at once or is the speed difference negligeable ?

도움이 되었습니까?

해결책

If the file isn't too large to fit in memory, it would be faster to read all the bytes into a MemoryStream and then read Uint16s from that stream. Like so:

byte[] data;
int size;
using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    size = (int) stream.Length;
    data = new byte[size];
    stream.Read(data, 0, size);
}

uint[] uintData = new uint[size / 2];
using (var memoryStream = new MemoryStream(data))
using (var reader = new BinaryReader(memoryStream))
    for (int i = 0; i < size / 2; i++)
        uintData[i] = reader.ReadUInt16();

// Done.

다른 팁

First, you don't need this line:

byte[] test = new byte[size];

because the following line

test = br.ReadBytes(size);

makes test point to another array. So,

byte[] test = br.ReadBytes(size);

suffices.


Regarding your question: Since BinaryReader.ReadBytes just performs Stream.Reads in a loop (you can verify this with ILSpy or by looking at the reference source code), I'd assume that the performance difference between your code examples is negligible. To be sure, I'd recommend that you do some measurements.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top