When extending a class, is there any difference in performance between polymorphism and composition? Take the following example using composition (in C++):
class Window
{
public:
Window(Renderer &renderer) : m_renderer(renderer)
{ }
void update()
{
....
m_renderer.draw(this);
}
private:
Renderer &m_renderer;
}
… and using polymorphism:
class Window : public Renderer
{
public:
virtual ~Window() {};
void update()
{
...
draw();
}
protected:
virtual void draw() = 0;
}
The composition version uses a reference as a member so I suppose that it requires a little more space, but is there any performance gain in either version?
Note: I have checked out similar post such as this, but is does not cover performance.
Thank you for your answers!
Well, if you pose the question like this, then yes there is a memory/speed trade-off.
1. Composition
2. Inheritance
So you might say that inheritance is slightly more costly… but really it’s just invisible. The overhead of a function call compared to the inner computation required for graphic rendering is just negligible.
On the other hand, the semantics differ. Whether you inherit or not is significant. Is you
WindowaRenderer? Does it make sense ?Write sane code first. Then optimize as (if !!!) needed.