4 ms·
Sorry I am not familiar with monomorphization. What does it mean in the context of Rust?
by StreamBright 7y ago
Sorry 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