What is the cost of inheritance?

前端 未结 7 1161
遥遥无期
遥遥无期 2020-12-06 07:11

This is a pretty basic question but I\'m still unsure:

If I have a class that will be instantiated millions of times -- is it advisable not to derive it from some o

7条回答
  •  生来不讨喜
    2020-12-06 08:05

    Largely, this depends upon the implementation. But there are some commonalities.

    If your inheritance tree includes any virtual functions, the compiler will need to create a vtable for each class - a jump table with pointers to the various virtual functions. Every instance of those classes will carry along a hidden pointer to its class's vtable.

    And any call to a virtual function will involve a hidden level of indirection - rather than jumping to a function address that had been resolved at link time, a call will involve reading the address from the vtable and then jumping to that.

    Generally speaking, this overhead isn't likely to be measurable on any but the most time-critical software.

    OTOH, you said you'd be instantiating and destroying millions of these objects. In most cases, the largest cost isn't constructing the object, but allocating memory for it.

    IOW, you might benefit from using your own custom memory allocators, for the class.

    http://www.cprogramming.com/tutorial/operator_new.html

提交回复
热议问题