Will C++ compilers automatically optimise the following code to calculate 3*i only once, and increment the result, or must the programmer code this?
void writeToArr开发者_开发百科ay(int i, int a, int b, int c)
{
array[3*i][1]=a;
array[3*i][2]=b;
array[3*i][3]=c;
}
Most optimizers will pick up on this, yes. However if you want to encourage the optimizer, here's how:
void writeToArray(int i, int a, int b, int c)
{
const int offset = 3 * i;
array[offset][1]=a;
array[offset][2]=b;
array[offset][3]=b;
}
When you enable optimization, almost all compilers will not only precompute the common index 3*i
but the pointer array + (3*i)*sizeof (*array)
.
Common Subexpression Elimination is one of the easiest and most commonly applied optimizations. In general, you can rely on this being done.
With modern compilers you can most of the time rely on the compiler doing the clever job and not try anything yourself. See for instance http://dl.fefe.de/optimizer-isec.pdf
精彩评论