Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ optimization

I'm working on some existing c++ code that appears to be written poorly, and is very frequently called. I'm wondering if I should spend time changing it, or if the compiler is already optimizing the problem away.

I'm using Visual Studio 2008.

Here is an example:

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

Here is how I would do it:

void someDrawingFunction(....)
{
  MyContext &c = GetContext();
  c.DrawSomething(...);
  c.DrawSomething(...);
  c.DrawSomething(...);
  .
  .
  .
}
like image 859
Tim Rupe Avatar asked Nov 26 '22 22:11

Tim Rupe


2 Answers

Don't guess at where your program is spending time. Profile first to find your bottlenecks, then optimize those.

As for GetContext(), that depends on how complex it is. If it's just returning a class member variable, then chances are that the compiler will inline it. If GetContext() has to perform a more complicated operation (such as looking up the context in a table), the compiler probably isn't inlining it, and you may wish to only call it once, as in your second snippet.

If you're using GCC, you can also tag the GetContext() function with the pure attribute. This will allow it to perform more optimizations, such as common subexpression elimination.

like image 92
Adam Rosenfield Avatar answered Nov 29 '22 12:11

Adam Rosenfield


If you're sure it's a performance problem, change it. If GetContext is a function call (as opposed to a macro or an inline function), then the compiler is going to HAVE to call it every time, because the compiler can't necessarily see what it's doing, and thus, the compiler probably won't know that it can eliminate the call.

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

like image 26
Michael Kohne Avatar answered Nov 29 '22 13:11

Michael Kohne