没有 LINQ(例如,在针对 .Net 2.0 时很有用):
byte[] bytearray = Array.ConvertAll<int, byte>(arrayint, (z) => (byte)z);
嗯,是的,比 LINQ 快得多:
测试代码(可以改进,但这给出了一个想法):
private static void Main(string[] args)
{
int[] arrayint = new int[40000];
arrayint[0] = 99;
arrayint[1] = 157;
arrayint[2] = 1;
arrayint[3] = 45;
byte[] bytearray;
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
bytearray = Array.ConvertAll<int, byte>(arrayint, (z) => (byte)z);
}
sw.Stop();
Console.WriteLine("ConvertAll took {0} ms", sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
bytearray = arrayint.Select(z => (byte)z).ToArray();
}
sw.Stop();
Console.WriteLine("LINQ took {0} ms", sw.ElapsedMilliseconds);
Console.ReadLine();
}
结果:
ConvertAll 花了 1865 毫秒
LINQ 耗时 6073 毫秒