Just read a bunch of posts on traits/trait objects in Rust and it is not clear when to use static vs dynamic dispatch. Anyone have a one sentence tl;dr on when to use which?
@rustlang
-
-
Replying to @danbruder @rustlang
Static dispatch will be more performant and dynamic dispatch will result in smaller binaries, I think?
3 replies 1 retweet 6 likes -
Replying to @FreeMasen @rustlang
Thank you! I was missing the smaller binary size part for dynamic
1 reply 0 retweets 2 likes -
A very minor size difference. Prefer static where possible. Rust is trying to do the same — it’s aggressively trying to make your dynamic dispathes static if it can figure it out
1 reply 1 retweet 4 likes -
Replying to @sanbox_irl @danbruder and
On bigger codebases or on large objects that you move around the opposite is true, monomorphising is costly and slow to compile, and depending on the application the performance impact is minimal. I believe ripgrep relatively recently moved to preferring dyn dispatch, for example
1 reply 2 retweets 3 likes -
Replying to @ekuber @sanbox_irl and
I agree with your advice, but I don't think there have been any recent subatantive changes related to dispatch in ripgrep. ripgrep has always used bith, although it certainly heavily relies on monomorphization in specific areas for performance.
2 replies 1 retweet 4 likes -
Replying to @burntsushi5 @ekuber and
Also though I understand this being true, it feels like simply a failure of Rustc. With incremental builds, I don’t think this should be the case anymore
2 replies 1 retweet 1 like -
Replying to @sanbox_irl @ekuber and
I wouldn't frame it as a failure. Compilation times have gotten much faster sonce I started writing Rust almost six years ago. There is still a long way to go of course, but it has been getting better.
1 reply 1 retweet 1 like -
Replying to @burntsushi5 @ekuber and
“Failure” is harsh, but I mean that if compilation time drives users to less performant code, the fault is with the compiler, ultimately. It’s gotten much faster in even the last year and I’m happy with the rustlang team greatly
2 replies 0 retweets 1 like
Monomophization will never be free, no matter how fast your compiler is. It results in fatter binaries and other negative things. The beauty of trade offs is that sometimes we don't care about the downsides. Like using dynamic dispatch in code that isn't a performance bottleneck.
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.