C#中复制字符串数组的最快方法-直接赋值或使用Copy()、CopyTo()或Clone()

本文关键字:赋值 Copy Clone CopyTo 数组 字符串 复制 方法 | 更新日期: 2023-09-27 18:20:54

我试图通过使用以下代码找出复制字符串数组最快的方法:

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()、Direct、Copy(),但这并不是绝对一致的。你的经历是什么?你用得最多的是哪一个?为什么?

C#中复制字符串数组的最快方法-直接赋值或使用Copy()、CopyTo()或Clone()

Array.CopyTo只是Array.Copy的包装。也就是说,CopyTo本质上是这样做的:

void CopyTo(Array dest, int length)
{
    Array.Copy(this, dest, length);
}

因此Copy将比CopyTo稍微快(少一个间接)。

您的直接拷贝实际上并没有拷贝数组。它只是复制了参考资料。也就是说,给定这个代码:

    string[] directAnimals = new string[animals.Length];
    directAnimals = animals;

如果随后写入animals[0] = "Penguin";,则directAnimals[0]也将包含值"Penguin"

我怀疑Clone将与Array.Copy相同。它所做的就是分配一个新的数组并将值复制到其中

关于定时的一些注意事项:

你的测试工作量太少,无法准确计时。如果你想要有意义的结果,你必须多次执行每个测试。类似于:

copyTo.Start();
for (int i = 0; i < 1000; ++i)
{
    string[] copyToAnimals = new string[animals.Length];
    animals.CopyTo(copyToAnimals, 0);
}
copyTo.Stop();
Console.WriteLine("Copy to: " + copyTo.Elapsed);

对于这样的小阵列,1000次可能甚至不够。你可能需要一百万来看看是否有任何有意义的区别。

此外,如果在调试器中运行这些测试,结果将毫无意义。请确保在发布模式下编译,并在调试器分离的情况下运行。从命令行执行,或者在Visual Studio中使用Ctrl+F5。