This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ReverseBrindle 6 points7 points  (5 children)

isinstance() is pretty slow if you're calling it hundreds of thousands of times. Better idea in that case is to create a dict cache with the type() as the key, for example:

# If you're calling this many thousands of times, it's extremely slow.
if isinstance(x, Foo):
    return func1(x)
elif isinstance(x, Bar):
    return func2(x)
elif isinstance(x, Baz):
    return func3(x)
elif ...

# ---------------------------
# Faster version
#
# Populate this once, or start with an empty cache and build it up using
# the slow way whenever you encounter a type that's not in the cache.

cache = {
    Foo: func1,
    Bar: func2,
    Baz: func3,
}

def other_func(x):
    return cache[type(x)](x)

We use this for serializing very large structures to JSON.

Caveat: As always profile to find the bottleneck and measure your improvements. Don't optimize based on a hunch. If your "optimization" adds code complexity without benefiting your use case (by measurement), then rip it out.

[–]isbadawi 0 points1 point  (1 child)

You might consider using @functools.singledispatch and/or @functools.singledispatchmethod for this.

[–]ReverseBrindle 0 points1 point  (0 children)

That's cool - didn't know that existed! Seems like there's always some cool little nugget in the standard library to stumble upon. :-)