function pointer vs. inline
Aug 13, 2014 at 10:56am UTC
I need to make conditional function calls, inside a loop (few thousand iterations, hence looking for an efficient way).
The condition is set outside the loop though.
So I guess I could use a function pointer:
1 2 3 4 5
funcPtr = ( true ) ? &func1 : &func2;
for (...){
funcPtr(arg);
}
What about inline functions though, wouldn't that be faster? But it has the additional if/else.
1 2 3 4 5 6
for (...){
if ( true )
inlineFunc1(arg);
else
inlineFunc2(arg);
}
Common sense somehow tells me pointers to inline would be a contradiction.
Is all this actually worth thinking about, or does it fall into the realm of compiler optimisations?
(Using Xcode5/Clang)
Thanks!
Ci
Aug 13, 2014 at 11:33am UTC
Forks that must be evaluated at run time inside tight loops are forbidden.
1 2 3 4 5 6 7 8 9
if (true ){
for (...){
inlineFunc1(arg);
}
}else {
for (...){
inlineFunc2(arg);
}
}
You can remove the code duplication using templates:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <void F(Bar)>
struct Loop{
void operator ()(const Bar &a) const {
for (...){
F(a);
}
}
};
//...
if (true )
Loop<inlineFunc1>()(arg);
else
Loop<inlineFunc2>()(arg);
Last edited on Aug 13, 2014 at 11:34am UTC
Aug 13, 2014 at 11:33am UTC
Somewhere was discussion about what the compiler can do on
Functor vs
func-ptr . Scott Meyers, perhaps.
Depending on the details, you naturally have the option:
1 2 3 4 5 6 7 8 9 10 11
void loopfunc1() {
for (...) {
inlineFunc1(arg);
}
}
void loopfunc2() {
for (...) {
inlineFunc2(arg);
}
}
Or maybe a templated loopfunc can take the inlineFunc as template parameter (static bind) to prevent code duplication.
Edit :
slow
Anyway, you can always profile the different variants to see whether they differ.
Last edited on Aug 13, 2014 at 11:35am UTC
Aug 13, 2014 at 7:58pm UTC
Thanks!
Topic archived. No new replies allowed.