开发者

Design Pattern to replace nested loops

Is there any design pattern or some other way to replace the huge number of nested loops? The only purpose is performance enhancement.

e.g

for (int i=0; i<2000; i++)
{
    for (int j=0; j<2000; j++)
开发者_开发技巧    {
       for (int k=0; k<2000; k++)
       {

       }
    }
}


In general no. A design pattern is more about how you organise your code to make it comprehensible, maintainable extensible etc. By virtue of this, you might end up with more efficient code but not necessarily.

If your algorithm requires that you visit every element in a 3 dimensional data structure of size 2000, then no design pattern can help, you just have a n^3 algorithm and there's nothing you can do about this.

The only scope for improvement will be if your algorithm turns out to be naive and maybe visits more elements than is strictly required. harrisunderwork above alludes to this by asking if you are searching; if so, maybe there search algorithm can be made more efficient but again, this is not a question regarding design patterns.


for (int x=0; x < 2000*2000*2000; x++)
{
    // you can calculate here real values of i,j,k if you need this for smth
    // do something
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜