Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Static vs Dynamic Dispatch #44

Open
insanitybit opened this issue Jul 20, 2022 · 1 comment
Open

Static vs Dynamic Dispatch #44

insanitybit opened this issue Jul 20, 2022 · 1 comment

Comments

@insanitybit
Copy link

There are cases where static dispatch is faster than dynamic and there are cases where dynamic can be faster than static. It would be worth noting what the impact of both is.

ex:

Dynamic Dispatch implies at least a vtable lookup, and usually an additional allocation (I think you can do stack dyns now? Maybe not). Static Dispatch can increase icache pressure.

An alternative when you actually need multiple types implementing a single trait would be to use an enum, which can compile down to a jump table. Jump tables can increase pressure on the instruction cache though.

@muskaantiwari
Copy link

(continuing, maybe in simple terms...)

  • In Rust, static dispatch is implemented using generics, while dynamic dispatch is implemented using trait objects.
  • Performance area in dynamic dispatch is vtable lookup and trait object allocations. Implies this is not favorable for huge types. But for unknown types, this might become necessary. Enums might be better alternatives to it in some cases (for more info see the enums video of @ThePrimeagen).
  • Static dispatch can increase instruction cache (icache) pressure, especially for huge generic types. Because the code for each type is duplicated at compile time, leading to larger binary sizes and more cache misses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants