c - Which for loop is better? -


The question below was asked in the Microsoft Placement Examination. I do not know who would be better, can someone help me?

Code 1:

  int MAX = 1000; Int a [MAX] [MAX]; For (i = 0; i & lt; MAX; i ++) for (j = 0; j and lt; max; j ++) a [j] [i] = i * j;  

Code 2:

  int (j = 0; j and lt; max; j ++) a [i] [j] = i * J. Max = 1000 for (i = 0; i & lt; MAX; i ++); Int a [max] [max];  

Which is correct?

  1. Code 1 is fast
  2. Code 2 is fast
  3. Both are the same

In the difference how they use memory, your array is kept in this way:

  line 0 - 1000 Integer line 1 - 1000 integer etc.  

Now, your first loop will access one [0] [0] , then a [1] [0] , e.t.c. So it's going to find row 0, then find and update column 0. Then it is to find line 1, find column 0 in it and access it. So you are accessing memory everywhere - essentially it is bad for the CPU cache randomly because it has to be reloaded with every memory access.

Accesses your second loop a [0] [0] , then a [0] [1] , then a [ 0] [2] , etc. So this line underlines 0, then it reaches the column in sequence. This is good for the processor cache, and it will execute shortly because it does not need to be repeated often.


Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -