aboutsummaryrefslogtreecommitdiff
path: root/docs/dev
diff options
context:
space:
mode:
Diffstat (limited to 'docs/dev')
-rw-r--r--docs/dev/style.md32
1 files changed, 32 insertions, 0 deletions
diff --git a/docs/dev/style.md b/docs/dev/style.md
index 59067d234..20f1b6253 100644
--- a/docs/dev/style.md
+++ b/docs/dev/style.md
@@ -186,6 +186,31 @@ impl Person {
186} 186}
187``` 187```
188 188
189## Constructors
190
191Prefer `Default` to zero-argument `new` function
192
193```rust
194// Good
195#[derive(Default)]
196struct Foo {
197 bar: Option<Bar>
198}
199
200// Not as good
201struct Foo {
202 bar: Option<Bar>
203}
204
205impl Foo {
206 fn new() -> Foo {
207 Foo { bar: None }
208 }
209}
210```
211
212Prefer `Default` even it has to be implemented manually.
213
189## Avoid Monomorphization 214## Avoid Monomorphization
190 215
191Rust 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*. 216Rust 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*.
@@ -223,6 +248,8 @@ fn frbonicate(f: impl AsRef<Path>) {
223 248
224# Premature Pessimization 249# Premature Pessimization
225 250
251## Avoid Allocations
252
226Avoid writing code which is slower than it needs to be. 253Avoid writing code which is slower than it needs to be.
227Don't allocate a `Vec` where an iterator would do, don't allocate strings needlessly. 254Don't allocate a `Vec` where an iterator would do, don't allocate strings needlessly.
228 255
@@ -242,6 +269,8 @@ if words.len() != 2 {
242} 269}
243``` 270```
244 271
272## Push Allocations to the Call Site
273
245If allocation is inevitable, let the caller allocate the resource: 274If allocation is inevitable, let the caller allocate the resource:
246 275
247```rust 276```rust
@@ -257,6 +286,9 @@ fn frobnicate(s: &str) {
257} 286}
258``` 287```
259 288
289This is better because it reveals the costs.
290It is also more efficient when the caller already owns the allocation.
291
260## Collection types 292## Collection types
261 293
262Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`. 294Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`.