vftable performance penalty vs. switch statement

前端 未结 5 1461
遥遥无期
遥遥无期 2020-12-24 02:00

C++ question here. I have a system where I\'m going to have hundreds of mini-subclasses of a given superclass. They all will have a \"foo\" method that does something. Or

5条回答
  •  一向
    一向 (楼主)
    2020-12-24 02:42

    There's been some research on this topic in the field of virtual machine design. Generally, a switch statement is going to be faster, a lot of virtual machines use switch semantics as opposed to virtual lookup. Theoretically, one would assume that a virtual table - being a constant time algorithm - will be faster, but we have to examine how the hardware sees a virtual table.

    A switch statement is easier for the compiler to inline. This is a huge consideration, the actual act of calling a virtual function is minimal, however, pushing and popping the entire stack frame is necessary because the compiler has no idea which function will be called at run-time.

    Branch prediction and hardware prefetch should be easier on a switch statement, although modern architectures are getting better at predicting virtual calls.

    A lot of code that uses virtual dispatch requires the use of heap based allocation schemes. Dynamic memory allocation is a bottleneck in a lot C++ applications.

提交回复
热议问题