如何找出哪个嵌套for循环更好? [英] How to find out which nested for loop is better?

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

问题描述

有人问我一个问题: 在以下两种情况中哪一个是最快的:

Somebody asked me a question: Which one is the fastest among the below two scenario:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 5; j++)
    {
        count++;
    }
}

情况2:假设int count = 0;

for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 10; j++)
    {
        count++;
    }
}

在两种情况下,计数的最终值都是50. 但是我不确定哪一个会更快?我认为CASE II速度更快,但不确定...

In both the scenario's the final valuse of count will be 50. But I am not sure which one will be faster? I think CASE II is faster but not sure...

如果有人能对此有所启发,那就太好了.哪个更快,为什么?

It will be great if anyone can throw some light on it. which is faster and why?

推荐答案

这是我可以想到的唯一示例,您可以在哪里迭代哪个变量

this is the only example i can think of where it matters which variable you iterate where

int array[n][m];
//fast
for (int i=0;i<n;i++)
{ for(int j=0;j<m;j++)
  { count+=array[i][j];
  }
}
//slow
for (int i=0;i<m;i++)
{ for(int j=0;j<n;j++)
  { count+=array[j][i];
  }
}

第二个比较慢,因为您没有一个又一个地迭代内存中的位置,而是因为您一次跳过了m个位置.处理器会缓存访问位置之后立即定位的内存位置.

the second one is slower because you don't iterate the locations in memory one after the other, but because you jump by m locations at a time. the processor caches the memory locations positioned immediately after an accessed location.

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

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