0

Inside one of my class methods I declare several local variables like this:

    int findClosestPoint(double rRadius)
    {
        int iXIndexMult, iYIndexMult, iZIndexMult, iVoxelX, iVoxelY, iVoxelZ, iPIndexVoxel, iV, iV_From, iV_To;
        double rDist, rDX, rDY, rDZ;
        double rRadius2 = rRadius*rRadius;
        double rMinDist = rRadius2;
        int iFoundVertex = -1;

        // do stuff

        retrun iFoundVertex;
    }

I'm calling this method thousands of times so I thought it would be a good idea to move variables declaration from method body to the class, so I recieved something like this:

    int findClosestPoint(double rRadius)
    {
        rRadius2 = rRadius*rRadius;
        rMinDist = rRadius2;
        iFoundVertex = -1;

        // do stuff

        retrun iFoundVertex;
    }

I was suprised because the result of this operation was significant performance drop in my program.

Can anyone may explain to me why that happened?

Amadeusz
  • 1,488
  • 14
  • 21
  • 1
    Some potential reading: http://stackoverflow.com/questions/16699247/what-is-cache-friendly-code – lcs Mar 07 '16 at 15:14
  • 1
    It's not really surprising. By doing that, you block optimization from your compiler... don't try to optimize for your compiler, you mislead it! – Garf365 Mar 07 '16 at 15:16
  • It could be a number of things. For instance, as cocarin suggests cache lines. Another possibility is that optimizations are blocked. For example, `rRadius2` (I'm assuming, based off the name) doesn't change during the function and so the compiler can optimize it to `const`. As a member variable, it can't do that anymore. – R_Kapp Mar 07 '16 at 15:18
  • 1
    Measure first, optimize later. – Daniel Daranas Mar 07 '16 at 15:23
  • Avoid global variables. Here they are not global, but useless global variables for the class, making any class object bigger than needed. –  Mar 07 '16 at 15:31

2 Answers2

0

You relocated that context from local stack/register to (perhaps) heap memory. Heap requires more time to access than stack.

  • Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Enamul Hassan Mar 15 '16 at 03:39
0

Always keep the scope of your variables as small as possible. This not only gives the compiler more optimization options but also makes your code more readable and avoids side effects.

What exactly causes the performance drop in your case depends on your compiler and on what exactly your function is doing in the // do stuff section.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45