Virtual Functions

Virtual functions seem to inflict a performance cost in several ways:

  • The vptr (virtual table pointer) must be initialized in the constructor.
  • The vptr must be initialized in the constructor virtual function is invoked via pointer indirection. We must fetch the pointer to the function table and then access the correct function offset.
  • Inlining is a compile-time decision. The compiler cannot inline virtual functions whose resolution takes place at run-time.

The inability to inline a virtual function is its biggest performance penalty.

Key Points:

  • The cost of a virtual function stems from the inability to inline calls that are dynamically bound at run-time. The only potential efficiency issue is the speed gained from inlining if there is any. Inlining efficiency is not an issue in the case of functions whose cost is not dominated by call and return overhead.

Templates are more performance-friendly than inheritance hierarchies. They push type resolution to compile-time, which we consider to be free.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s