Known solution to avoid dynamic_cast slowness?

I need polymorphism at runtime, so I used dynamic_cast.
But now I had two problems - it dynamic_castwas very slow! (Scroll down for the test.)

In short, I decided to solve this problem using static_cast:

struct Base
{
    virtual ~Base() { }
    virtual int type_id() const = 0;

    template<class T>
    T *as()
    { return this->type_id() == T::ID ? static_cast<T *>(this) : 0; }

    template<class T>
    T const *as() const
    { return this->type_id() == T::ID ? static_cast<T const *>(this) : 0; }
};

struct Derived : public Base
{
    enum { ID = __COUNTER__ };  // warning: can cause ABI incompatibility
    int type_id() const { return ID; }
};

int main()
{
    Base const &value = Derived();
    Derived const *p = value.as<Derived>();  // "static" dynamic_cast
}

But I, of course, was not the first person to encounter this problem, so I thought it was worth considering:

Instead of coming up with such a home-made solution, is there a well-known model / library that I can use to solve this problem in the future?


Sample test

To understand what I'm talking about, try the code below - it dynamic_castwas about 15 times less than a simple call virtualon my machine (110 ms versus 1620 ms using the code below):

#include <cstdio>
#include <ctime>

struct Base { virtual unsigned vcalc(unsigned i) const { return i * i + 1; } };
struct Derived1 : public Base 
{ unsigned vcalc(unsigned i) const { return i * i + 2; } };
struct Derived2 : public Derived1
{ unsigned vcalc(unsigned i) const { return i * i + 3; } };

int main()
{
    Base const &foo = Derived2();
    size_t const COUNT = 50000000;
    {
        clock_t start = clock();
        unsigned n = 0;
        for (size_t i = 0; i < COUNT; i++)
            n = foo.vcalc(n);
        printf("virtual call: %d ms (result: %u)\n",
            (int)((clock() - start) * 1000 / CLOCKS_PER_SEC), n);
        fflush(stdout);
    }
    {
        clock_t start = clock();
        unsigned n = 0;
        for (size_t i = 0; i < COUNT; i++)
            n = dynamic_cast<Derived1 const &>(foo).vcalc(n);
        printf("virtual call after dynamic_cast: %d ms (result: %u)\n",
            (int)((clock() - start) * 1000 / CLOCKS_PER_SEC), n);
        fflush(stdout);
    }
    return 0;
}

virtual dynamic_cast static_cast, 79 ms, , ~ 25%!

+5
2

dynamic_cast (. ). , 7.5 , dynamic_cast.

+3

: http://www.stroustrup.com/isorc2008.pdf

, - , , , , ( dynamic_cast) .

, .

+2

All Articles