一、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