C#的ToArray性能 [英] C#: ToArray performance

查看:2017
本文介绍了C#的ToArray性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我承认我没有试图基准这一点,但我很好奇......

I admit I did not attempt to benchmark this, but I'm curious...

什么是 Enumerable.ToArray&LT的CPU /内存特性; T> (和其表弟 Enumerable.ToList< T> )?

由于的IEnumerable 事先不公布有多少元素它都有,我(可能天真)presume 的ToArray 将不得不猜测的初始阵列的尺寸,然后调整大小/重新分配阵列,如果第一猜测显得过小,则到如果第二猜测显得太小等再次调整其大小...这将使逊于线性的性能。

Since IEnumerable does not advertise in advance how many elements it has, I (perhaps naively) presume ToArray would have to "guess" an initial array size, and then to resize/reallocate the array if the first guess appears to be too small, then to resize it yet again if the second guess appears to be too small etc... Which would give worse-than-linear performance.

我可以想像,涉及(混合)列出更好的方法,但是这仍然需要一个以上的配置(虽然不是重新分配)和复制的比较一下,虽然它可能是,尽管架空线的整体。

有什么神奇发生在幕后,这避免了这种重复调整大小,使的ToArray 直线在空间和时间?

Is there any "magic" taking place behind the scenes, that avoids the need for this repetitive resizing, and makes ToArray linear in space and time?

更普遍的,有没有对BCL的性能特点是官方的文档?

More generally, is there an "official" documentation on BCL performance characteristics?

推荐答案

没有魔法。如果需要调整大小发生了。

No magic. Resizing happens if required.

请注意,这不是的总是的要求。如果的IEnumerable< T> .ToArray 又向工具的ICollection< T> ,那么 .Count之间属性用于pre-分配阵列(使算法的线性空间和时间)。如果不是,但是下列(粗)code执行:

Note that it is not always required. If the IEnumerable<T> being .ToArrayed also implements ICollection<T>, then the .Count property is used to pre-allocate the array (making the algorithm linear in space and time.) If not, however, the following (rough) code is executed:

    foreach (TElement current in source)
    {
        if (array == null)
        {
            array = new TElement[4];
        }
        else
        {
            if (array.Length == num)
            {
                // Doubling happens *here*
                TElement[] array2 = new TElement[checked(num * 2)];
                Array.Copy(array, 0, array2, 0, num);
                array = array2;
            }
        }
        array[num] = current;
        num++;
    }

请注意加倍当数组填满。

Note the doubling when the array fills.

无论如何,这通常是一个很好的做法,以避免调用 .ToArray() .ToList()除非你绝对需要它。需要讯问时直接查询往往是一个更好的选择。

Regardless, it's generally a good practice to avoid calling .ToArray() and .ToList() unless you absolute require it. Interrogating the query directly when needed is often a better choice.

这篇关于C#的ToArray性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆