0

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

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(),但并非绝对一致。你的经验是什么?你最常使用哪一个,为什么?

4

1 回答 1

1

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。

于 2013-07-03T15:20:23.610 回答