Optimization question

Hey guys!

Lets take a look at this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void DoSomething()
{
    //Something is done here ;)
}

class Base
{
public:
	Base(void (*function)()) : function(function) {}
     void (*function)();
};

class Derived : public Base
{
public:
    Derived() : Base(DoSomething) {}
};


Do you thing a compiler can optimize this so that Derived doesn't keep the function pointer in memory, but uses it as any other normal function? I personally think it will be possible since function won't be changed in Derived, but what do you guys think?
If you only plan to use this in this context i'd event mark void (*func)(); as const and then i'm pretty sure it'd be optimized away.
Yeah I knew that, but this way I leave the option available to reassign it later and I was wondering if it wouldn't lose its effecienty.
Last edited on
I don't think you should worry of this, there shouldn't be any efficiency difference between a function and a pointer to function
Why not? Maybe not in this case, but function pointers keep the pointer in memory per object right? And if I remember it right, class functions are usually inlined, and if not, at least it is not in memory per object.
Class function are inlined only if defined in the class body and the compiler decides to inline them
How member functions are stored and how objects access them is nod defined in the C++ standard
Last edited on
Wait a minute... I think everyone missed the subtle question.

When you call a function by name, the compiler generates a single CALL instruction (assuming intel) to
some memory location that is essentially known either at compile time or fixed up at load time by
the OS loader.

When you call a function by pointer, first the compiler has to generate code to read the memory
locations containing the function's address into a register, then generate a single CALL instruction to
the value stored in the register. That's 2 instructions (at least) vs. 1 above.

OP is asking can the compiler, through optimizations, turn this second case into the first one. The
answer is absolutely positively not under any circumstances. This is one of the performance benefits
to using templates, inlines, and function objects. In that case, yes, the compiler can avoid the second
case because it knows what function to call at compile time.
The second case also needs just one instruction, e.g. call [ebp+8].
That depends. If the function pointer is in a local variable on the stack or a parameter to the function, yes.
If the function pointer were a member of a struct, it may require more.

Topic archived. No new replies allowed.