]> git.lizzy.rs Git - rust.git/commitdiff
Avoid monomorphization
authorAleksey Kladov <aleksey.kladov@gmail.com>
Mon, 24 Aug 2020 10:49:36 +0000 (12:49 +0200)
committerAleksey Kladov <aleksey.kladov@gmail.com>
Mon, 24 Aug 2020 10:49:36 +0000 (12:49 +0200)
docs/dev/style.md

index 44f0956c247cb7c3a0555fcdb7f242cf05cdd4e5..ae69cf1a7438183407f8e5adfe0d3f742df0f97e 100644 (file)
@@ -231,6 +231,41 @@ if words.len() != 2 {
 }
 ```
 
+# Avoid Monomorphization
+
+Rust uses monomorphization to compile generic code, meaning that for each instantiation of a generic functions with concrete types, the function is compiled afresh, *per crate*.
+This allows for exceptionally good performance, but leads to increased compile times.
+Runtime performance obeys 80%/20% rule -- only a small fraction of code is hot.
+Compile time **does not** obey this rule -- all code has to be compiled.
+For this reason, avoid making a lot of code type parametric, *especially* on the boundaries between crates.
+
+```rust
+// Good
+fn frbonicate(f: impl FnMut()) {
+    frobnicate_impl(&mut f)
+}
+fn frobnicate_impl(f: &mut dyn FnMut()) {
+    // lots of code
+}
+
+// Not as good
+fn frbonicate(f: impl FnMut()) {
+    // lots of code
+}
+```
+
+Avoid `AsRef` polymorphism, it pays back only for widely used libraries:
+
+```rust
+// Good
+fn frbonicate(f: &Path) {
+}
+
+// Not as good
+fn frbonicate(f: impl AsRef<Path>) {
+}
+```
+
 # Documentation
 
 For `.md` and `.adoc` files, prefer a sentence-per-line format, don't wrap lines.