user997112
user997112

Reputation: 30645

Example of polymorphism preventing compiler optimization?

Cannot remember where I saw it now- but somewhere I read that dynamic polymorphism prevents the compiler from making various optimizations.

Besides inlining, could somebody please englighten me with any examples of such "missed" optimization opportunities which polymorphism prevents the compiler from making?

Upvotes: 4

Views: 259

Answers (2)

Jarod42
Jarod42

Reputation: 218118

With:

Derived d;
d.vMethod(); // that will call Derived::vMethod statically (allowing inlining).

With (unless one of Derived or Derived::vMethod is declared final in C++11):

void foo(Derived& d)
{
    d.vMethod(); // this will call virtually vMethod (disallowing inlining).
}

Virtual call has an additional cost (as indirection through the vtable).

C++11 introduces final keyword which may turn the last example in static call.

Upvotes: 2

epx
epx

Reputation: 1096

At least in C++, polymorphic objects must be in the form of pointers or references. Sometimes this prevents the possibility of putting them on stack variables, or List types, you need to use List. Stack variables spare dynamic allocations etc.

A call to Poly.vmethod() is always resolved at compile time, even if vmethod() is virtual, while Poly->vmethod() consults the virtual method table. (Well, if the method is virtual it is meant to be polymorphic. Static methods are statically resolved in either case.)

Return value optimization (RVO) is another trick that does not have place when returning pointers or references. RVO is typically implemented by passing a hidden parameter: a pointer to a memory region, that is filled with the "returned" object. The size and the type of this region must be perfectly known at compile time.

Upvotes: 0

Related Questions