小循环中的大循环总是比大循环中的小循环快?

问题描述:

我刚刚阅读了

I just read this post, and wonder if we can draw the conclusion that a big loop within a small loop must always run faster than a small loop within a big one, no matter what the code does inside the nested loop? Take an example.

int m, n; 
m = 1000000;
n = 10;

片段A

for (int i = 0; i < n; i++)         
    for (int j=0; j < m; j++)               
       {       
           DoSomething();        
       }

摘要B

for (int j = 0; j < m; j++)               
    for (int i=0; i < n; i++)           
       {       
          DoSomething();          
       }

我们可以说,无论DoSomething()实际做什么,代码段A的运行总比代码段B的运行快?

Can we say that, no matter what DoSomething() actually does, snippet A always runs faster thant snippet B?

更新
正如@stackmate所指出的,我想将此问题扩展为两个

UPDATE
As pointed out by @stackmate, I want to expand this question into two

  1. 当嵌套循环中的代码是DoSomething()时,这意味着DoSomething()与变量i和j没有关系.什么是性能差异?

  1. When the code inside nested loop is DoSomething() which means DoSomething() has nothing to do with variable i and j. What is the performance difference?

当嵌套循环中的代码是DoSomething(i,j)时,这意味着DoSomething(i,j)与变量i和j有关联.性能上有什么区别?

When the code inside nested loop is DoSomething(i, j) which means DoSomething(i, j) has relateship with variable i and j. What is the performance difference?

对于您的问题,没有特定的答案.决定是否快速的参数是您在循环中所做的事情.例如,假设您要添加2个数组并将它们存储在第三个数组中:

There cannot be a specific answer to your question. The parameter deciding whether it will be fast or not is what you are doing inside the loops. For example say you are adding 2 arrays and storing them in a third array:

Code 1:
for(int i = 0; i < 1000; i++)
{
    for(int j = 0; j < 1000000; j++)
         C[i][j] = A[i][j] + B[i][j];
}

Code 2:
for(int i = 0; i < 1000000; i++)
{
    for(int j = 0; j < 1000; j++)
         C[j][i] = A[j][i] + B[j][i];
}

代码1将比代码2快得多.原因是缓存.请查看问题以了解更多详细信息.答案非常有用,我没有必要在这里再次解释缓存的概念.

Code 1 will be much faster than code 2. The reason is cache. Take a look at this question for more details. The answers are superbly informative and there is no point in me explaining the concept of cache again over here.