在C#/ VB.NET/.NET中,哪个循环运行得更快,for或者foreach?
自从我读了一个for循环工程快于foreach环路很久以前我以为这对所有集合,泛型集合,所有阵列,等真正站在
我搜索谷歌并发现了一些文章,但其中大多数都没有结果(阅读文章的评论)和开放式.
什么是理想的是列出每个场景和相同的最佳解决方案.
例如(只是它应该如何的一个例子):
for比...更好foreachIList(非泛型)字符串 - foreach比...更好for在网上找到的一些参考文献:
foreach或不是foreach,这就是问题forvsforeach
[编辑]
除了可读性方面,我对事实和数据非常感兴趣.有些应用程序的最后一英里性能优化受到挤压很重要.
哪个代码段会提供更好的性能?以下代码段是用C#编写的.
1.
for(int counter=0; counter<list.Count; counter++)
{
list[counter].DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
2.
foreach(MyType current in list)
{
current.DoSomething();
}
Run Code Online (Sandbox Code Playgroud) 当我在Python中使用while循环或for循环时,我发现了问题.看起来人们更喜欢使用for循环(更少的代码行?).是否有任何具体情况我应该使用其中一种?这是个人偏好的问题吗?到目前为止我读过的代码让我觉得它们之间存在很大差异.
在.NET中,使用"foreach"迭代IEnumerable的实例会创建一个副本吗?那么我是否应该使用"for"而不是"foreach"?
我写了一些代码来证明这一点:
struct ValueTypeWithOneField
{
private Int64 field1;
}
struct ValueTypeWithFiveField
{
private Int64 field1;
private Int64 field2;
private Int64 field3;
private Int64 field4;
private Int64 field5;
}
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("one field");
Test<ValueTypeWithOneField>();
Console.WriteLine("-----------");
Console.WriteLine("Five field");
Test<ValueTypeWithFiveField>();
Console.ReadLine();
}
static void Test<T>()
{
var test = new List<T>();
for (int i = 0; i < 5000000; i++)
{
test.Add(default(T));
}
Stopwatch sw = new Stopwatch();
for (int i = 0; i < 5; …Run Code Online (Sandbox Code Playgroud) from collections import *
ignore = ['the','a','if','in','it','of','or']
ArtofWarCounter = Counter(ArtofWarLIST)
for word in ArtofWarCounter:
if word in ignore:
del ArtofWarCounter[word]
Run Code Online (Sandbox Code Playgroud)
ArtofWarCounter是一个Counter对象,包含战争艺术中的所有单词.我正试图ignore从ArtofWarCounter 中删除单词.
追溯:
File "<pyshell#10>", line 1, in <module>
for word in ArtofWarCounter:
RuntimeError: dictionary changed size during iteration
Run Code Online (Sandbox Code Playgroud) 我想循环一个三维数组.有没有比以下更有效(或更快)的替代方法?
for i, j, k in itertools.product(*map(xrange, (len(x), len(y), len(z))))
Run Code Online (Sandbox Code Playgroud)
在这个例子中,x,y和z是三个一维数组.
我的源代码是这样的,我不想要列表的值.
for i, j, k in itertools.product(*map(xrange, (len(x0), len(y0), len(z0)))):
print "p[%d][%d][%d] = %d" % (x0[i], y0[j], z0[k], p[i][j][k])
Run Code Online (Sandbox Code Playgroud)
p 是3d阵列
可能重复:
对于C#中的vs foreach循环
让我们说我有一个集合
List <Foo> list = new List <Foo>();
现在哪个愚蠢的循环运行得更快,原因如下:
for(int i = 0; i <list.Count; i ++)
要么
foreach(Foo foo列表中)
c# ×4
performance ×3
python ×3
.net ×2
for-loop ×2
foreach ×2
collections ×1
containers ×1
counter ×1
generics ×1
loops ×1
python-2.7 ×1
value-type ×1