问题描述
var fillData = new List<int>();
for (var i = 0; i < 100000; i++)
{
fillData.Add(i);
}
var stopwatch1 = new Stopwatch();
stopwatch1.Start();
var autoFill = new List<int>();
autoFill.AddRange(fillData);
stopwatch1.Stop();
var stopwatch2 = new Stopwatch();
stopwatch2.Start();
var manualFill = new List<int>();
foreach (var i in fillData)
{
manualFill.Add(i);
}
stopwatch2.Stop();
当我把 4 从 stopwach1
和 stopwach2
,<$ C $结果C> stopwatch1 的值不是 stopwatch2
。这意味着的AddRange
总是比的foreach
更快。没有人知道为什么?
When I take 4 results from stopwach1
and stopwach2
, stopwatch1
has always lower value than stopwatch2
. That means addrange
is always faster than foreach
.Does anyone know why?
推荐答案
潜在的,的AddRange
可以检查在那里传递给它的价值实现的IList
或的IList&LT; T&GT;
。如果是这样,就可以知道有多少值都在范围内,因而多少空间需要分配......而的foreach
循环可能需要重新分配数次。
Potentially, AddRange
can check where the value passed to it implements IList
or IList<T>
. If it does, it can find out how many values are in the range, and thus how much space it needs to allocate... whereas the foreach
loop may need to reallocate several times.
此外,即使分配后,名单,其中,T&GT;
可以使用的执行批量复制到下面的数组(其实施范围的IList&LT; T&GT ;
,当然)
Additionally, even after allocation, List<T>
can use IList<T>.CopyTo
to perform a bulk copy into the underlying array (for ranges which implement IList<T>
, of course.)
我怀疑你会发现,如果您再次使用,但尝试测试 Enumerable.Range(0,100000)
为 fillData code>,而不是
名单,其中,T&GT;
,两人将需要大约相同的时间
I suspect you'll find that if you try your test again but using Enumerable.Range(0, 100000)
for fillData
instead of a List<T>
, the two will take about the same time.
这篇关于为什么比的AddRange使用foreach循环更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!