Enlico
Enlico

Reputation: 28490

How to measure difference in performance between virtual function+inheritance and std::function member w/o inheritance?

tl;dr

Is the benchmark I present below a fair way to compare inheritance-based vs std::function-based approach to polymorphism?

Full question

If one needs different objects that implement the same interface in different ways, and also needs to be able to put them under a container and swap one with another at run-time, the most popular solution is to use inheritance:

struct Base {
    virtual void f() = 0;
    virtual ~Base() = default;
};
struct Derived1 : Base {
    virtual void f();
};
struct Derived2 : Base {
    virtual void f();
};

Another solution is to have a single class, but swap the virtual method for a std::function:

struct Foo {
    std::function<void()> f{};
};
auto foo1 = Foo{[]{ return /* impl like Derived1 */; }};
auto foo2 = Foo{[]{ return /* impl like Derived2 */; }};

(Some questions about the difference between the two approaches are here, here, and here.)


However, regardless of other pros and cons of either solution, I'm curious to measure the difference in performance with a benchmark.

I understand that the performance will obviously vary based on how std::function is implemented as well as on the compiler and the options passed to it, the operating system, and who knows what else.

But with all these factors being held fixed, I think one can measure the difference in performance, if it exists at all.

I should clarify that my intention is see first-hand that indeed the difference between the two approaches is to be considered negligible unless in very peculiar usecases, as I've understood from the linked questions and other sources. Or to prove that my understanding is wrong and there is indeed an important difference in performance.


My attempt to write a benchmark is here:

A few explanations about various bits of it:

The result,

Upvotes: 1

Views: 86

Answers (0)

Related Questions