编辑其他选项和下面稍微扩展的问题.
考虑一个类体的这个人为的抽象例子.它演示了执行"for"迭代的四种不同方法.
private abstract class SomeClass
{
public void someAction();
}
void Examples()
{
List<SomeClass> someList = new List<SomeClass>();
//A. for
for (int i = 0; i < someList.Count(); i++)
{
someList[i].someAction();
}
//B. foreach
foreach (SomeClass o in someList)
{
o.someAction();
}
//C. foreach extension
someList.ForEach(o => o.someAction());
//D. plinq
someList.AsParallel().ForAll(o => o.someAction());
Run Code Online (Sandbox Code Playgroud)
编辑:从答案和研究中添加一些选项.
//E. ParallelEnumerable
ParallelEnumerable.Range(0, someList.Count - 1)
.ForAll(i => someList[i].someAction());
//F. ForEach Parallel Extension
Parallel.ForEach(someList, o => o.someAction());
//G. For Parallel Extension
Parallel.For(0, someList.Count …Run Code Online (Sandbox Code Playgroud) 我只是试图确定每个"if"语句对我的C#应用程序在具有大量迭代的循环中使用时的性能的影响.我没有找到关于这个的主题所以我创建了这个.
对于测试,我做了2个循环:一个没有"if",一个有一个"if"语句.代码如下.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace IfPerformance
{
class Program
{
static void Main(string[] args)
{
int N = 500000000;
Stopwatch sw = new Stopwatch();
double a = 0, b = 0;
bool f;
sw.Restart();
for (int i = 0; i < N; i++)
{
a += 1.1;
f = a < N;
}
sw.Stop();
Console.WriteLine("Without if: " + sw.ElapsedMilliseconds + " ms");
a = 0;
sw.Restart();
for (int i = …Run Code Online (Sandbox Code Playgroud)