当我决定在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之外,我的代码比内置代码快几倍或至少一样快.所以现在的问题是,为什么会发生这种情况?