我已经对C#中的List进行了一些速度测试。这是我无法解释的结果。我希望有人能弄清楚正在发生的事情。
如果在cloneList.Add(next)之前调用了cloneList.RemoveAt(cloneList.Count-1),则为1000次迭代的毫秒数:x毫秒。
如果在cloneList.Add(next)之前未调用cloneList.RemoveAt(cloneList.Count-1),则进行1000次迭代的毫秒数:至少20x毫秒。
看来,如果再有一条语句,我的代码会快20倍(请参见下面的代码):
Stopwatch stopWatch = new Stopwatch();
Random random = new Random(100);
TimeSpan caseOneTimeSpan = new TimeSpan();
TimeSpan caseTwoTimeSpan = new TimeSpan();
int len = 1000;
List<int> myList = new List<int>();
myList.Capacity = len + 1;
// filling the list
for (int i = 0; i < len; i++)
myList.Add(random.Next(1000));
// number of tests (1000)
for (int i = 0; i < 1000; i++)
{
List<int> cloneList = myList.ToList();
int next = random.Next();
// case 1 - remove last item before adding the new item
stopWatch.Start();
cloneList.RemoveAt(cloneList.Count - 1);
cloneList.Add(next);
caseOneTimeSpan += stopWatch.Elapsed;
// reset stopwatch and clone list
stopWatch.Reset();
cloneList = myList.ToList();
// case 2 - add without removing
stopWatch.Start();
cloneList.Add(next);
caseTwoTimeSpan += stopWatch.Elapsed;
stopWatch.Reset();
}
Console.WriteLine("Case 1: " + caseOneTimeSpan.TotalMilliseconds);
Console.WriteLine("Case 2: " + caseTwoTimeSpan.TotalMilliseconds);
Console.WriteLine("Case 2 / Case 1: " + caseTwoTimeSpan.TotalMilliseconds / caseOneTimeSpan.TotalMilliseconds);
最佳答案
这应该使差异消失:
// reset stopwatch and clone list
stopWatch.Reset();
cloneList = myList.ToList();
cloneList.Capacity = cloneList.Capacity + 1; // add this
// case 2 - add without removing
stopWatch.Start();
cloneList.Add(next);
caseTwoTimeSpan += stopWatch.Elapsed;
关于c# - 在列表(C#)上添加新项目时的速度差异很奇怪,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12414703/