4 ms·
Also executable size because of monomorphization. I'm kinda worried that the top comment by goefft mentions an example module that uses Serde which is particula
by majewsky 7y ago
Also executable size because of monomorphization. I'm kinda worried that the top comment by goefft mentions an example module that uses Serde which is particularly vulnerable to this kind of bloat.
- StreamBright 7y agoSorry I am not familiar with monomorphization. What does it mean in the context of Rust?
- masklinn 7y agoIf you define a generic function, the function is "duplicated" for each concrete type it's used with. If the function is large, or it's used with many different types, that leads to a lot of semi-duplicates and extra code in the binary. For instance there will be one version of Vec::push for each type used in a Vec<T>. A common pattern to mitigate this (though not always applicable) is a generic trampoline to a monomorphic function for the cases where the genericity is mostly a matter of convenience e.g. let's say that your function works on strings, but for convenience you take a `T: AsRef<str>` (callers can pass anything from which a string reference can be created cheaply), the first thing you do is `let s = s.as_ref()` so the vast majority of the function is monomorphic (it takes only one set of concrete types as input). Rather than this: fn my_function(s: T) where T: AsRef<str> { let s = s.as_ref(); // do stuff with s: &str } you can do this: fn my_function(s: T) where T: AsRef<str> { _my_function(s.as_ref()); } fn _my_function(s: &str) { // do stuff with s } unless rustc decides to inline just _my_function into my_function (which would be quite odd), this leads to very little monomorphization and bloat.
- StreamBright 7y agoThis was quite educational, thanks!
- mkl 7y agoTo add to masklinn's answer, here is some more information: https://rustwasm.github.io/twiggy/concepts/generic-functions-and-monomorphization.html https://rustwasm.github.io/twiggy/concepts/generic-functions... https://doc.rust-lang.org/book/ch10-01-syntax.html https://doc.rust-lang.org/book/ch10-01-syntax.html