簡體   English   中英

C#BinaryReader明顯較慢。 另類?

[英]C# BinaryReader notably slower. Alternative?

對於我的項目,我需要從文件中編寫UInt16,UInt32,字節和字符串。 我從寫這樣的簡單類開始:

    public FileReader(string path)  //constructor
    {
        if (!System.IO.File.Exists(path))
            throw new Exception("FileReader::File not found.");

        m_byteFile = System.IO.File.ReadAllBytes(path);
        m_readPos = 0;
    }
    public UInt16 getU16()   // basic function for reading
    {
        if (m_readPos + 1 >= m_byteFile.Length)
            return 0;

        UInt16 ret = (UInt16)((m_byteFile[m_readPos + 0])
                            + (m_byteFile[m_readPos + 1] << 8));
        m_readPos += 2;
        return ret;
    }

我認為最好使用已經存在的BinaryReader,所以我嘗試了一下,但是我發現它比我的方法要慢。 有人可以解釋為什么會這樣,如果還有另一個我可以用來加載文件並從中讀取文件的類?

〜阿杜拉

您將所有數據預先存儲在內存中的數組中,而BinaryReader一次從源(我認為它是磁盤上的文件)流式傳輸字節。 我猜您可以通過向其傳遞從內存數組中讀取的流來加快速度:

Stream stream = new MemoryStream(byteArray);
//Pass the stream to BinaryReader

請注意,通過這種方法,您需要立即將整個文件填充到內存中,但是我想這對您來說是可以的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM