for循环优化 [英] Optimisation of for loop

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

问题描述

大家好我正在写当前应该尽可能快地运行一些C#code,通常是拿一个单核心100%,约25分钟。我需要code保持单核与运行在多个内核此code也不会那么大运行该项目多次并发的利益

Hi guys i'm writing some c# code that is currently supposed to run as fast as possible, usually taking up a single core at 100% for about 25min. I need the code to remain single core as the benefit of running this code across multiple cores will not be as great as running this project multiple times concurrently

在code的问题如下:

The code in question is as follows

public Double UpdateStuff(){

    ClassA[] CAArray = ClassA[*a very large number indeed*];
    Double Value = 0;
    int length = CAArray.Length;

    for (int i= 0; i< length ; i++)
        {
         Value += CAArray[i].ClassB.Value * CAArray[i].Multiplier;
        }  
    return Value;
}

的code这个区域根据探查负责应用程序的负载的78%,因此似乎是一个很好的候选人进行优化。

This area of the code is responsible for 78% of the load of the application according to profilers and thus seems a good candidate for optimisation.

!!!注:此功能已经改变,从返回类型为void返回类型双,这是伪code,而不是实际的code,就可以轻松的阅读

!!!Note : the function has been changed from return type void to return type Double, this is pseudocode and not actual code to allow easier reading

要澄清:.NET,C#4.0,Visual Studio 2010中,目标机:在Windows Server 2008 x64的

To Clarify: .net, c#4.0, visual studio 2010, target machine : windows server 2008 x64

编辑:进一步说明:在这种情况下所有变量是公开的,而不是属性。在CAArray值[I] .ClassB.Value将永远改变,不能对匹配的双打

Further clarification : all variables in this context are public and not properties. The values in CAArray[i].ClassB.Value will be forever changing doubles that cannot be pair matched.

推荐答案

您应该删除这样的:

int length = CAArray.Length;

和本替换循环:

for (int i= 0; i < CAArray.Length; i++)
{
    Value += CAArray[i].ClassB.Value * CAArray[i].Multiplier;
} 

存储像你原来的code的长度不实际的减慢的C#code(反直觉的,我知道)。这是在每次循环,因为如果你直接在for循环有Array.Length,抖动会跳过做一个数组边界检查。

Storing the length like your original code does actually slows down C# code (counter-intuitive, I know). This is because if you have Array.Length directly in the for loop, the jitter will skip doing an array bounds-check on each iteration of the loop.

另外,我强烈建议并行化这一进程。要做到这一点最简单的方法就是

Also, I strongly suggest parallelizing this process. The simplest way to do this is

CAArray.AsParallel().Sum(i => i.ClassB.Value * i.Multiplier);

虽然你可以的可能的获得更多的速度,没有LINQ(尽管你再不必担心管理多个线程的低层次的细节)。

although you could potentially get even more speed without LINQ (though you then need to worry about the low level details of managing multiple threads).

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

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