How much overhead should I expect from a wrapper function
This question is more or less similar to this Extend an existing API: Use default argument or wrapper function? but sufficiently different.
Please read.I have a class Foo that has function oldFunc that is used in many parts of my program.
In order to introduce new behaviour to Foo I implemented newFunc and made it private so that callers to oldFunc keep using the same API but can get the new behaviour if they set a flag by calling setUseType() function.Pseudo code follows:
class Foo
{
public:
Foo(){ useNew = false;}
void setUseType(bool useType){ useNew = useType;}
std::开发者_如何学Cstring oldFunc(int r)
{
if(useNew )
{
return newFunc(r);
}
return std::string("Some value after doing some work");
}
private:
std::string newFunc(int r){ return std::string("Some value after doing some work");}
bool useNew;
};
Question oldFunc
is called many times ( millions of times) inside a loop.
newFunc
inside oldFunc
.
Theoretically if oldFunc
and newFunc
where indentical in implementation is there a reason to expect
calls with a flag setUseType(true)
to be slower?You could measure it. Then you would know for sure. (At least for comparison purposes).
In this particular case, there will be no overhead on any non-idiotic compiler as the function will be inlined. Your code would be equivalent to:
class Foo
{
public:
Foo(){ useNew = false;}
void setUseType(bool useType){ useNew = useType;}
std::string oldFunc(int r)
{
if(useNew )
{
return std::string("Some value after doing some work");//newFunc inlined here
}
return std::string("Some value after doing some work");
}
private:
bool useNew;
};
If it were not inlined, there would be an extra jump for the call to the new function. That's where all the extra computation time goes into. This extra jump will most likely cause a lot less delay, even considering millions of calls. I suggest you do some profiling if you really do have speed issues and figure out the real bottleneck - most likely not the extra call.
I think any modern compiler will optimize the code such that it won't be more expensive to call newFunc() through oldFunc() than it is to call oldFunc() directly.
But note that you've added an if statement that will be evaluated every time oldFunc() is called, no matter if you are using the old and new functions. So now you've made all calls to oldFunc() a tiny bit slower.
The overhead of adding the if statement could be in the noise or could be significant, it depends. You should measure how long it takes to call the original oldFunc() 1,000,000 times, then measure the same thing with the if statement added. If the difference is significant you may want to look into other ways of allowing the client to select which method to call that avoid the if statement, for example through a member function pointer.
精彩评论