我试图找出使用以下代码复制字符串数组的最快方法:
static void Main(string[] args)
{
Stopwatch copy = new Stopwatch();
Stopwatch copyTo = new Stopwatch();
Stopwatch direct = new Stopwatch();
Stopwatch clone = new Stopwatch();
string[] animals = new string[1000];
animals[0] = "dog";
animals[1] = "cat";
animals[2] = "mouse";
animals[3] = "sheep";
for (int i = 4; i < 1000; i++)
{
animals[i] = "animal";
}
copy.Start();
string[] copyAnimals = new string[animals.Length];
Array.Copy(animals, copyAnimals, animals.Length);
copy.Stop();
Console.WriteLine("Copy: " + copy.Elapsed);
copyTo.Start();
string[] copyToAnimals = new string[animals.Length];
animals.CopyTo(copyToAnimals, 0);
copyTo.Stop();
Console.WriteLine("Copy to: " + copyTo.Elapsed);
direct.Start();
string[] directAnimals = new string[animals.Length];
directAnimals = animals;
direct.Stop();
Console.WriteLine("Directly: " + direct.Elapsed);
clone.Start();
string[] cloneAnimals = (string[])animals.Clone();
clone.Stop();
Console.WriteLine("Clone: " + clone.Elapsed);
}
在大多数情况下,最快的排名是:CopyTo()、Clone()、Directly、Copy(),但并非绝对一致。你的经验是什么?你最常使用哪一个,为什么?