哪个for循环更快 [英] Which for loop is faster

查看:103
本文介绍了哪个for循环更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个循环更快???



第一循环(繁体)




Which loop is faster ???

1st Loop (Traditional)


List<string> Days = new List<string>();
                for (int i = 1; i <= 31; i++)
                {
                    Days.Add(i.ToString("00"));
                }





或第二个并行循环:





Or 2nd Parallel for loop:

List<string> Days = new List<string>();
System.Threading.Tasks.Parallel.For(1, 31, i =>
                {
                    Days.Add(i.ToString("00"));
                });









谢谢





Thanks

推荐答案

您可以从使用Parallel.For令人失望的表现 [ ^ ]


解决方案1由_Asif_ [ ^ ]非常好,即使不包含确切的答案。



传统的循环快于 Parrarel循环甚至Linq方法也是:



Solution 1 by _Asif_[^] is very good, even if does not contain exact answer.

Traditional for loop is faster than Parrarel loop and even Linq method too:

List<string> Days = Enumerable.Range(1,31).Select(x=>x.ToString("00")).ToList();





执行时间:



Time of execution:

1) traditional:  00:00.070 s
2) parrarel:     00:00.197 s
3) linq:         00:00.330 s


循环无法并行化,因为Days.Add()需要顺序处理。因此parallel.for只是增加开销而不提高性能。



要关注的关键是是否有一个变量随着每次执行而被修改。



在这种情况下,每次执行都会更改Days,并且混合执行顺序会混淆最终列表中元素的顺序。



PS:我刚刚意识到这种评估并不完全正确。我只考虑了命令Days.Add()而没有考虑嵌入函数参数的命令:i.ToString()。后者可以并行化,因为它不依赖于处理顺序。但是,如果不立即将字符串存储在列表中,则创建其他临时字符串的开销可能超过并行化字符串转换的好处。所以它不像我上面概述的那样清晰。
The loop can't be parallelized to start with, since Days.Add() requires sequential processing. Therefore parallel.for just adds overhead without improving performance.

The key thing to look for is whether there is a variable that gets modified with each execution.

In this case, Days is changed with each execution, and mixing the order of execution will mix up the order of elements in the final list.

P.S.: I just realized this assessment isn't entirely correct. I've only considered the command Days.Add() without considering the command embedded with the function parameter: i.ToString(). The later can be parallelized, as it doesn't depend on the order of processing. However, if you don't immediately store the string in the list, the overhead of creating an additional temporary string probably outweighs the benefit of parallelizing the string conversion. So it isn't as clear cut as I outlined it above.


这篇关于哪个for循环更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆