加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么c#内置的IO类比自制的类更快?

发布时间:2020-12-15 03:52:25 所属栏目:百科 来源:网络整理
导读:当我决定在C#中自己实现 Java ByteBuffer时,我以为它会比MemoryStream BinaryWriter / BinaryReader快.我通过ILSpy看了他们的源码,并且有很多检查和帮助方法调用,而在我的实现中,我直接使用底层的字节数组.但是,当测试表明重型内置类的方法调用比我的轻型方
当我决定在C#中自己实现 Java ByteBuffer时,我以为它会比MemoryStream BinaryWriter / BinaryReader快.我通过ILSpy看了他们的源码,并且有很多检查和帮助方法调用,而在我的实现中,我直接使用底层的字节数组.但是,当测试表明重型内置类的方法调用比我的轻型方法的调用速度快几乎两倍时,我感到非常惊讶.

例如:

public void WriteBytes(Byte[] buffer,Int32 offset,Int32 count)
{
    this.EnsureFreeSpace(count);

    Buffer.BlockCopy(buffer,offset,this.buffer,this.position,count);

    this.position += count;
    if (this.length < this.position)
    {
        this.length = this.position;
    }
}

public void ReadBytes(Byte[] buffer,Int32 count)
{
    this.EnsureDataExist(count);

    Buffer.BlockCopy(this.buffer,buffer,count);

    this.position += count;
}

private void EnsureFreeSpace(Int32 count)
{
    if (this.buffer.Length - this.position < count)
    {
        throw new InvalidOperationException();
    }
}

private void EnsureDataExist(Int32 count)
{
    if (this.length - this.position < count)
    {
        throw new InvalidOperationException();
    }
}

?1.5-2倍慢

memoryStream.Write(...)
memoryStream.Read(...)

在这个简单的测试中

Byte[] temp = new byte[64];
stopWatch.Restart();
for (int i = 0; i < 100000; i++)
{
    ms.Write(temp,temp.Length);
    ms.Position = 0;
    ms.Read(temp,temp.Length);
    ms.Position = 0;
}
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds);

stopWatch.Restart();
for (int i = 0; i < 100000; i++)
{
    mb.WriteBytes(temp,temp.Length);
    mb.Position = 0;
    mb.ReadBytes(temp,temp.Length);
    mb.Position = 0;
}
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds);

为什么?

在所有的测试优化启用.在调试模式下,平均差异如我所说?1.7倍.在发布模式?1.3倍,少但仍然存在.

编辑
感谢我的建议,我发现在Visual Studio之外,我的代码比内置代码快几倍或至少一样快.所以现在的问题是,为什么会发生这种情况?

解决方法

我的看法是你没有正确地测试其性能.此主题已经覆盖了好几次,我发现Eric Lippert的这个博客系列非常有启发性: http://tech.pro/blog/1293/c-performance-benchmark-mistakes-part-one

作为一个捷径,请执行以下操作:将整个测试代码放在for循环中并运行多次,比较输出并总是丢弃第一个结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读