function pointer vs. inline

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
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
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
Thanks!
Topic archived. No new replies allowed.