[C#]BitConverter.GetBytes和位运算、数组拷贝Array.CopyTo、Buffer.BlockCopy和for循环的运行效率对比

文章通过性能测试得出,位运算在转换整数到字节数组时效率高于BitConverter.GetBytes方法。同时,推荐使用Buffer.BlockCopy而不是Array.CopyTo进行数组拷贝,因为前者具有更高的效率。
摘要由CSDN通过智能技术生成

一、BitConverter.GetBytes和位运行

结论:位运算效率较高,但BitConverter.GetBytes用起来比较方便。

int Id = 0x11011123;
byte[] frame = new byte[4];

Stopwatch stopwatch1 = Stopwatch.StartNew();
for (int i = 0; i < 100000000; i++)
{
    frame[0] = (byte)(Id >> 24);
    frame[1] = (byte)(Id >> 16);
    frame[2] = (byte)(Id >> 8);
    frame[3] = (byte)Id;
}
stopwatch1.Stop();
Console.WriteLine($"位运算 : {stopwatch1.ElapsedMilliseconds}ms");

stopwatch1.Restart();
for (int i = 0; i < 100000000; i++)
{
    BitConverter.GetBytes(Id);
}
stopwatch1.Stop();
Console.WriteLine($"BitConverter.GetBytes : {stopwatch1.ElapsedMilliseconds}ms");

二、数组拷贝的三种方法对比

结论:Array.CopyTo效率比较低,建议使用Buffer.Bloc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值