At the GoingNative event, during the Interactive Panel on Day2 at the 9 minute mark, Chandler Carruth says:
Pointers create aliasing problems. They slow d
Consider the following function:
void f(float* lhs, float* rhs, float* out, int size) {
for(int i = 0; i < size; i++) {
out[i] = *lhs + *rhs;
}
}
What's the fastest version of this function? Probably, you hoist *lhs + *rhs
out of the loop. The problem is what happens when the pointers alias. Imagine what that optimization does if I call it like this:
float arr[6] = { ... };
f(arr, arr + 1, arr, 6);
As you can see, the problem is that *lhs + *rhs
cannot be hoisted out of the loop, because out[i]
modifies their values. In fact, the compiler can't hoist any logic out of the loop. So the compiler cannot perform the "obvious" optimization, because if the parameters alias the logic is now incorrect. However, if the floats are taken by value, then the compiler knows they can't alias and can perform the hoist.
Of course, this function is pretty silly, but it demonstrates the point.