中国开发网: 论坛: .NET/C#: 贴子 501328
没脾气2x: 测试三种读 struct 值的方法的效率
这样的一个结构体:

[code=c#] [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1 )] public struct ZIP_FILEDATA_HEAD { public UInt16 wVersion; public UInt16 wFlags; public UInt16 wMethod; public UInt32 dwDosTime; public UInt32 dwCrc; public UInt32 dwCompressedSize; public UInt32 dwOriginalSize; public UInt16 lenName; public UInt16 lenExtra; } [/code]

第一段代码:
[code=c#] static public class BufferHelper { static public Object BytesToStruct( byte[] bytes, Type structType ) { int size = Marshal.SizeOf( structType ); IntPtr buffer = Marshal.AllocHGlobal( size ); try { Marshal.Copy( bytes, 0, buffer, size ); return Marshal.PtrToStructure( buffer, structType ); } finally { Marshal.FreeHGlobal( buffer ); } } static public Object ReadStruct( BinaryReader reader, Type structType ) { int size = Marshal.SizeOf( structType ); byte[] bytes = new byte[size]; reader.Read( bytes, 0, size ); return BytesToStruct( bytes, structType ); } } public class TestA: Test { public override void Run() { ZIP_FILEDATA_HEAD header = (ZIP_FILEDATA_HEAD)BufferHelper.ReadStruct( m_reader, typeof( ZIP_FILEDATA_HEAD ) ); } } [/code]

第二段代码:
[code=c#] public class TestB: Test { public override void Run() { const int HeaderSize = 26; byte[] buffer = new byte[HeaderSize]; m_reader.Read( buffer, 0, HeaderSize ); ZIP_FILEDATA_HEAD header; header.wVersion = System.BitConverter.ToUInt16( buffer, 0 ); header.wFlags = System.BitConverter.ToUInt16( buffer, 2 ); header.wMethod = System.BitConverter.ToUInt16( buffer, 4 ); header.dwDosTime = System.BitConverter.ToUInt32( buffer, 6 ); header.dwCrc = System.BitConverter.ToUInt32( buffer, 10 ); header.dwCompressedSize = System.BitConverter.ToUInt32( buffer, 14 ); header.dwOriginalSize = System.BitConverter.ToUInt32( buffer, 18 ); header.lenName = System.BitConverter.ToUInt16( buffer, 22 ); header.lenExtra = System.BitConverter.ToUInt16( buffer, 24 ); } } [/code]

[code=c#] public class TestC: Test { public override void Run() { ZIP_FILEDATA_HEAD header; header.wVersion = m_reader.ReadUInt16(); header.wFlags = m_reader.ReadUInt16(); header.wMethod = m_reader.ReadUInt16(); header.dwDosTime = m_reader.ReadUInt32(); header.dwCrc = m_reader.ReadUInt32(); header.dwCompressedSize = m_reader.ReadUInt32(); header.dwOriginalSize = m_reader.ReadUInt32(); header.lenName = m_reader.ReadUInt16(); header.lenExtra = m_reader.ReadUInt16(); } } [/code]


其中 m_reader 是 BinaryReader 创建于一个以 Open 方式打开的 FileStream
上述 Test 方法各执行 500,000 次

第一种方法: 4.093s
第二种方法: 2.266s
第三种方法: 2.469s


从程序简洁来说,我更喜欢用第一种代码,但是速度太慢,希望能够进一步优化
Notemper2x 3.1 ( ̄ε( ̄#)
没脾气2x 之 个人综合篇: http://notemper2x.cndev.org/
我的 panoramio 相册: http://panoramio.com/user/zhaixudong
我的 flickr相册: http://www.flickr.com/photos/notemper2x/



QQ号20250出售,售价400,000元整(5位、皇冠80级、VIP7)a

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录