0

I was asked by someone to determine which one of codes would run faster. No doubt, I went with the first one as it looked much obvious to me but I didn't exactly know why the first one would be faster. P.S. I tried both of the codes and based of my observation the first approach is faster.

First approach:

struct A
{
    int x[32];
};
A* arr = new A[100];

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 32; j++)
    {
        arr[i].x[j] = 1;
    }
}

The second approach:

struct A
{
    int x[32];
};
A* arr = new A[100];
for (int i = 0; i < 32; i++)
{
    for (int j = 0; j < 100; j++)
    {
        arr[j].x[i] = 1;
    }
}
Chris Loonam
  • 5,735
  • 6
  • 41
  • 63
armques
  • 117
  • 6
  • 6
    *Cache locality* – Eugene Sh. Mar 02 '20 at 20:56
  • 3
    When you are selling Girl Scout Cookies door to door, what is faster, going to each house on a street (house number 100, 102, 104, 106 on First Street, then house 100, 102, 104, 106 on Second Street, then Third Street) or going to each street, then each address (First Street house 100, then Second Street House 100, the Third Street house 100, the First Street House 102,…)? Certain parts of computer memory are organized to keep consecutive memory addresses together. Using them together is faster. – Eric Postpischil Mar 02 '20 at 20:59
  • @EugeneSh. Thank you, I just did a quick search on cache locality and it answered my question. – armques Mar 02 '20 at 21:13

0 Answers0