# Performance of functools.singledispatch

**URL:** <https://discuss.python.org/t/performance-of-functools-singledispatch/17648>\
**Category:** Ideas\
**Created:** [July 24, 2022, 8:08pm UTC](https://discuss.python.org/t/performance-of-functools-singledispatch/17648 "2022-07-24T20:08:15Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![oscarbenjamin](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/oscarbenjamin/32/1209_2.png) [@oscarbenjamin](https://discuss.python.org/u/oscarbenjamin)\
**Post date:** [July 24, 2022, 9:11pm UTC](https://discuss.python.org/t/performance-of-functools-singledispatch/17648/4 "2022-07-24T21:11:34Z")

</div>

This is also something that I’ve thought about. It would be great to make more use of `singledispatch` (e.g. see the last part of my comment [here](https://discuss.python.org/t/numeric-generics-where-do-we-go-from-pep-3141-and-present-day-mypy/17155/12)) but it is just too slow right now. I agree that a reimplementation in C makes sense. Potentially if `singledispatch` was heavily used (as it is in some other languages) it would make sense to have its own CPython opcodes or something more deeply integrated than just a C implementation for calling the function.

If `singledispatch` was used heavily then there are two main things to consider for performance:

1. Import time (if the `singledispatch` decorator was used many times during import of commonly used modules).
2. Per-call overhead.

Your benchmark times the second of those two points but the first is also important (more important for many applications that don’t actually call the function!).

The overhead identified in the wrapper function should be something that can be made small by a C implementation but after that the basic dict lookup in `dispatch_cache` is potentially slow for common use cases. If `singledispatch` was used heavily then you would probably find that most functions would have only a small number of registered types so it’s possible that at the C level something faster than a dict lookup could be used for the dispatch.

---

_[View the full topic](https://discuss.python.org/t/performance-of-functools-singledispatch/17648)._
