Polymorphic Dispatch: Virtual Function vs CRTP

Question 50 / 51 Correct so far: 0 (0 answered)

Snippet A

Virtual Call

struct Transformer {
    virtual double transform(double x) const = 0;
    virtual ~Transformer() = default;
};

struct ScaleTransformer : Transformer {
    double transform(double x) const override { return x * kBase; }
};

double applyAll(Transformer* t, int n) {
    double val = 1.0;
    for (int i = 0; i < n; ++i)
        val = t->transform(val);
    return val;
}

double result = applyAll(&t, kCallCount);
Snippet B

Crtp Call

template <typename Derived>
struct Transformer {
    double transform(double x) const {
        return static_cast<const Derived*>(this)->transformImpl(x);
    }
};

struct ScaleTransformer : Transformer<ScaleTransformer> {
    double transformImpl(double x) const { return x * kBase; }
};

template <typename T>
double applyAll(const Transformer<T>& t, int n) {
    double val = 1.0;
    for (int i = 0; i < n; ++i)
        val = t.transform(val);
    return val;
}

double result = applyAll(t, kCallCount);
Shared test data (shared-setup)
constexpr int kCallCount = 100000;
constexpr double kBase = 1.000001;

Which snippet is faster?

Select the correct answer(s)