3

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 writeToArray(int i, int a, int b, int c)
{
   array[3*i][1]=a;
   array[3*i][2]=b;
   array[3*i][3]=c;
}
3
  • 2
    Don't worry about this until you're sure it's a bottleneck. Commented Jul 21, 2011 at 15:22
  • 5
    Just a side note (I can't answer your question directly) that it might be more ideal for you to do the calculation before hand and use it instead of 3*i in each index because if the algorithm ever changes you have to replace multiple lines. Keeping the calculation in one location helps for code maintainability. Commented Jul 21, 2011 at 15:22
  • @TheCapn - If the algorithm changes, perhaps he needs 2*i and 4*i for different indexes. Why worry now? Wait until it changes. Commented Jul 21, 2011 at 15:44

4 Answers 4

7

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I really like this formulation. In some (most?) cases, a little pat int the back for the optimizer is not unwarranted. Besides, this code looks cleaner anyways.
5

When you enable optimization, almost all compilers will not only precompute the common index 3*i but the pointer array + (3*i)*sizeof (*array).

Comments

3

Common Subexpression Elimination is one of the easiest and most commonly applied optimizations. In general, you can rely on this being done.

Comments

3

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

1 Comment

Good reference! If we write simple code, the compiler will more likely understand it too. If we are too "smart", neither we nor the compiler can make anything out of the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.