【发布时间】:2012-12-16 07:15:11
【问题描述】:
我已经测试了 List<string> 与 IEnumerable<string>
使用 for 和 foreach 循环进行迭代,列表是否可能更快?
这是我能找到的几个链接中的 2 个,这些链接公开表明迭代 IEnumerable 优于 List。
我的测试是从一个包含 URL 列表的文本文件中加载 10K 行。
我首先将它加载到 List 中,然后将 List 复制到 IEnumerable
List<string> StrByLst = ...method to load records from the file .
IEnumerable StrsByIE = StrByLst;
所以每个都有 10k 个项目类型 <string>
在每个集合上循环 100 次,即 100K 次迭代,结果是
List<string> 比IEnumerable<string> 快了惊人的50 x
这是可以预测的吗?
- 更新
这是进行测试的代码
string WorkDirtPath = HostingEnvironment.ApplicationPhysicalPath;
string fileName = "tst.txt";
string fileToLoad = Path.Combine(WorkDirtPath, fileName);
List<string> ListfromStream = new List<string>();
ListfromStream = PopulateListStrwithAnyFile(fileToLoad) ;
IEnumerable<string> IEnumFromStream = ListfromStream ;
string trslt = "";
Stopwatch SwFr = new Stopwatch();
Stopwatch SwFe = new Stopwatch();
string resultFrLst = "",resultFrIEnumrable, resultFe = "", Container = "";
SwFr.Start();
for (int itr = 0; itr < 100; itr++)
{
for (int i = 0; i < ListfromStream.Count(); i++)
{
Container = ListfromStream.ElementAt(i);
}
//the stop() was here , i was doing changes , so my mistake.
}
SwFr.Stop();
resultFrLst = SwFr.Elapsed.ToString();
//forgot to do this reset though still it is faster (x56??)
SwFr.Reset();
SwFr.Start();
for(int itr = 0; itr<100; itr++)
{
for (int i = 0; i < IEnumFromStream.Count(); i++)
{
Container = IEnumFromStream.ElementAt(i);
}
}
SwFr.Stop();
resultFrIEnumrable = SwFr.Elapsed.ToString();
更新...最终
将计数器移到 for 循环之外,
int counter = ..count用于 IEnumerable 和 List
然后按照@ScottChamberlain 的建议将 counter(int) 作为项目总数传递。 重新检查所有东西都已到位,现在结果比 IEnumerable 快 5 %。 因此得出结论,按场景使用 - 用例......完全没有性能差异......
【问题讨论】:
-
请发布实际代码....
-
@MitchWheat 会做......现在
-
那么,每次调用
SwFr.Elapsed时您会得到什么值,这是一个调试版本吗? -
我认为我不会太相信继续解释
Differences between EXE and DLL的信息来源。但值得指出的是,您实际上并没有枚举列表,而是每次都在i获取元素,而不是要求.Next() -
@nick_w 我认为 10k 件物品还不够,我在内部结束后放置了一个外部循环将其关闭,但将塞子留在内部 - 外部内部(10k 件物品一次)。
标签: c# performance collections