我已经测试了 List<string>
对比IEnumerable<string>
用 for
迭代和 foreach
循环,List 是否可能更快?
这些是我能找到的几个公开声明性能更好的链接中的两个 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 倍
这是可以预测的吗?
- 更新
这是进行测试的代码
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%。 所以得出结论,按场景使用 - 用例......根本没有性能差异......
最佳答案
你做错了什么。
您获得的时间应该彼此非常接近,因为您运行的代码本质上是相同的。
IEnumerable 只是一个接口(interface),由 List 实现,因此当您在 IEnumerable 引用上调用某些方法时,它最终会调用 List 的相应方法。
IEnumerable 中没有代码实现 - 这就是接口(interface) - 它们只指定类应该具有的功能,但没有说明它是如何实现的。
关于c# - 简单 List<string> 到 IEnumerable<string> 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899362/