Skip to content

Commit fc3e591

Browse files
committed
Avoid monomorphization
1 parent e65d48d commit fc3e591

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/dev/style.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,41 @@ if words.len() != 2 {
231231
}
232232
```
233233

234+
# Avoid Monomorphization
235+
236+
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*.
237+
This allows for exceptionally good performance, but leads to increased compile times.
238+
Runtime performance obeys 80%/20% rule -- only a small fraction of code is hot.
239+
Compile time **does not** obey this rule -- all code has to be compiled.
240+
For this reason, avoid making a lot of code type parametric, *especially* on the boundaries between crates.
241+
242+
```rust
243+
// Good
244+
fn frbonicate(f: impl FnMut()) {
245+
frobnicate_impl(&mut f)
246+
}
247+
fn frobnicate_impl(f: &mut dyn FnMut()) {
248+
// lots of code
249+
}
250+
251+
// Not as good
252+
fn frbonicate(f: impl FnMut()) {
253+
// lots of code
254+
}
255+
```
256+
257+
Avoid `AsRef` polymorphism, it pays back only for widely used libraries:
258+
259+
```rust
260+
// Good
261+
fn frbonicate(f: &Path) {
262+
}
263+
264+
// Not as good
265+
fn frbonicate(f: impl AsRef<Path>) {
266+
}
267+
```
268+
234269
# Documentation
235270

236271
For `.md` and `.adoc` files, prefer a sentence-per-line format, don't wrap lines.

0 commit comments

Comments
 (0)