C ++ optimization

I am working on some existing C ++ code that seems to be poorly written and is often called. I am wondering if I should spend time changing it or if the compiler is already optimizing the problem.

I am using Visual Studio 2008.

Here is an example:

void someDrawingFunction(....) { GetContext().DrawSomething(...); GetContext().DrawSomething(...); GetContext().DrawSomething(...); . . . } 

Here's how I do it:

 void someDrawingFunction(....) { MyContext &c = GetContext(); c.DrawSomething(...); c.DrawSomething(...); c.DrawSomething(...); . . . } 
+4
source share
6 answers

If you are sure this is a performance issue, change it. If GetContext is a function call (as opposed to a macro or inline function), then the compiler is going to HAVE to call it every time, because the compiler cannot see what it is doing, and therefore the compiler probably won. I don’t know that this can eliminate the call.

Of course, you need to make sure that GetContext ALWAYS returns the same, and this optimization is safe.

+11
source

Do not guess where your program spends time. First, profile to find bottlenecks, and then optimize them.

As for GetContext() , it depends on how complex it is. If it simply returns a member variable of the class, then it is likely that the compiler will include it. If GetContext() needs to perform a more complex operation (for example, searching for a context in a table), the compiler probably does not insert it, and you can simply call it once, as in the second fragment.

If you use GCC, you can also mark the GetContext() function GetContext() pure attribute. This will allow him to perform more optimizations, such as eliminating a common subexpression .

+25
source

If it is logically correct to do this in the second way, that is, call GetContext () once several times, this will not affect your program logic, I would do it in the second way, even if you have his profile and prove that it isn’t anyway, so that the next developer looking at this code will not ask the same question again.

+8
source

Obviously, if GetContext () has side effects (I / O, updating globals, etc.), than the proposed optimization will lead to different results.

Therefore, if the compiler cannot somehow detect that GetContext () is clean, you must optimize it yourself.

+2
source

If you're interested in what the compiler does, take a look at the build code.

+1
source

This is such a simple change, I would do it.
Fix it faster than discuss it.

But do you really have a problem?
Just because it is called often does not mean that it is often called TOO.
If it seems like a piggy, try it on to see what he is spending time on.
Most likely, this is not something you would have guessed.

0
source

All Articles