0

If I have many classes that use other classes with purely virtual interfaces can the compiler optimize this to not have a virtual call in Release Mode with full optimizations enabled?

For instance I have a class HardwareBuffer that contains a pointer to IHardwareResourceManager that has a virtual method:

virtual void ReleaseBuffer(HardwareBuffer* buffer) = 0;

and in the Release method of HardwareBuffer, I call

m_pHardwareResourceManager->Release(this);

There is a single class Render that inherits IHardwareResourceManager, where I actually implement the virtual Release method. When I create a HardwareBuffer, I set its m_pHardwareResourceManager to the Renderer itself.

Can the call to IHardwareResourceManager::Release in the Release method of HardwareBuffer be devirtualized?

bames53
  • 86,085
  • 15
  • 179
  • 244
ulak blade
  • 2,515
  • 5
  • 37
  • 81
  • Your formatting hurts my eyes. Can you make this more readable? – crashmstr Sep 11 '13 at 16:10
  • this might be a little more readable as code. If I understand you correctly, I would say that in most cases virtual functions do not be optimized away. Check out http://stackoverflow.com/questions/2141726/can-you-cache-a-virtual-function-lookup-in-c for more information. – MrSynAckSter Sep 11 '13 at 16:13
  • There are a few cases where the type of a variable, even if its used in a polymorphic way, its unknown at compile-time, so when you are worried about virtual functions performance (VTABLE and its inherent instructions-cache fights), static-polymorphism through CRTP could be a good alternative – Manu343726 Sep 11 '13 at 16:33
  • So, code something like this: http://pastebin.com/MwiSceUD? – bames53 Sep 11 '13 at 16:38

1 Answers1

0

I don't know when MSVC could accomplish it, but I do know that, in general, one would have to trace m_pHadwareResourceManager all the way back to the construction of Render. It has to be careful: a DLL could always create a new instance of IHardwareRResourceManager and provide it to your application. This is quite a daunting task, unless you allocated the Render object on the stack.

That being said, indirect lookups from a VTABLE like this are AGGRESSIVELY optimized at the hardware level, because they occur so often. Make sure you profile before assuming the virtual function call is a large cost. For example, I would not be surprised if, on x64, the indirect lookup is cheaper than the prologue and epilogue of the function you are calling.

For a comparison: DirectX uses COM, which has a comparable indirect lookup on every function call.

Cort Ammon
  • 10,221
  • 31
  • 45