Hello,

Is there any way to have fast dispatch based on the type of a variable?

I'm talking about code of the form:

t = type(var)
if t is int:
        i(v)
elif t is long:
        l(v)
elif t is float:
        f(v)
elif t is str:
        s(v)
elif t is unicode:
        u(v)
...

I have tried these ideas:
 - Having the types as keys in a dict and the functions as lambdas.
- Creating a list from min(type_hashes) to max(type_hashes) (with lambdas as list values) and indexing in it with hash(var_type) - min(type_hashes)

But both were slower than the multiple ifs.

The ideal case would be to have an optimization like C/C++ compilers do to switch statements, where they would create a binary search over the multiple cases like below:

Assuming that:

hash(int) < hash(long) < hash(float) ....

t=hash(type(var))
if t < hash(float):
        if t < hash(long):
                i(v)
        else:
                l(v)
else:
        if t< hash(unicode):
                s(v)
        else:
                u(v)

The problem in Python is that the order of type_hashes is not constant. So it is not possible to create the binary search code.

Kind regards,

l.
_______________________________________________
pypy-dev mailing list
pypy-dev@python.org
https://mail.python.org/mailman/listinfo/pypy-dev

Reply via email to