c++pointersoptimizationpaging

Within c++ function, pointer vs indexed array


This question is similar to what has been asked earlier but I think memory paging is not considered. So, I am posing the similar question again here:

// version 1
int nums[100];
int* pNum = nums;
for(int i=0;i<100;i++,pNum++){
  foo(pNum);
}

// version 2
for(int i=0;i<100;i++){
  foo(nums[i]);
}

Which version would be faster? Previously, it was said that generated assembly code would be very similar since both versions require incrementing the position of memory address but considering a very large array, would memory paging performance change significantly? Since one of them requires a type long shift but other one requires a shift from the base memory address of the array? I know it is very platform/compiler dependent but still want to know the common practice of people, especially working with large data types like image processing or scientific computing? Thanks.


Solution

  • The general consensus is that for primitive types, there is no difference. Most compilers will generate the exact same code for this (presumably you meant foo(*pNum)).