优化“;“补丁”;过程

本文关键字:过程 补丁 优化 | 更新日期: 2023-09-27 18:26:28

对于某些项目,我需要覆盖Files,但由于用户可能同时也会使用其他程序编辑此文件,因此我不经常在运行时保留流,而是将所有数据保存在字节数组中。保存程序时,应该只保存它编辑过的区域,而不是整个文件。我已经(非常糟糕)写了一个这样做的例程,但它预计会很慢,我不知道如何提高这里的性能。实际上,我只是在整个数组中循环,并不像看上去那么聪明:

    public Boolean Patch(string path)
    {
        FileStream fs = new FileStream(path, FileMode.Open);
        BinaryReader br = new BinaryReader(fs);
        BinaryWriter bw = new BinaryWriter(fs);
        if (fs.Length != this.rawdata.Length)
            throw new ArgumentException();
        for (int i = 0; i < this.rawdata.Length; ++i )
        {
            if (br.ReadByte() != rawdata[i])
            {
                fs.Position--;
                bw.Write(rawdata[i]);
            }
        }
        fs.Close();
        return true;
    }

优化“;“补丁”;过程

您对硬盘驱动器(或任何其他流)的每次访问都是昂贵的。转换您的代码以使用下一个X(例如1024)字节的缓存副本进行读取,并使用Y(即1024)字节进行写入。

我不完全理解你的代码应该做什么,但如果你想在流之间复制一个文件,你的功能应该是:

private const int BUFFER_SIZE = 1024;
void copy(BinaryReader inStream, BinaryWriter outStream)
{
    byte[] cache = new byte[BUFFER_SIZE];
    int readCount = 0;
    while ((readCount = inStream.Read(cache, 0, BUFFER_SIZE)) != 0)
    {
        outStream.Write(cache, 0, readCount);
    }
}

在本例中,BUFFER_SIZE不要太小(因此批量读取和写入会很有效),也不要太大——溢出内存
在您的代码示例中,您每次读取一个字节(即BUFFER_SIZE = 1),因此这会减慢应用程序的速度。

编辑:添加了需要编写的代码:

public Boolean Patch(string path)
    {
        const int BUFFER_SIZE = 512;
        // VERY IMPORTANT: The throw operation will cause the stream to remain open the function returns.
        using (FileStream fs = new FileStream(path, FileMode.Open))
        {
            BinaryReader br = new BinaryReader(fs);
            BinaryWriter bw = new BinaryWriter(fs);
            if (fs.Length != this.rawdata.Length)
                throw new ArgumentException();
            byte[] cache = new byte[BUFFER_SIZE];
            int readCount = 0, location = 0;
            while ((readCount = br.Read(cache, 0, BUFFER_SIZE)) != 0) 
            {
                int changeLength = 0;
                for (int j = 0; j < readCount; j++)
                {
                    if (cache[j] != rawdata[j + location])
                    {
                        changeLength++;
                    }
                    else if (changeLength > 0)
                    {
                        fs.Position = location + j - changeLength;
                        bw.Write(rawdata, location + j - changeLength, changeLength);
                        fs.Position = location + j;
                        changeLength = 0;
                    }
                }
                location += readCount;
            } 
            return true;
        }
    }