aboutsummaryrefslogtreecommitdiff
path: root/docs/dev/style.md
diff options
context:
space:
mode:
Diffstat (limited to 'docs/dev/style.md')
-rw-r--r--docs/dev/style.md34
1 files changed, 33 insertions, 1 deletions
diff --git a/docs/dev/style.md b/docs/dev/style.md
index aed15cee9..389649398 100644
--- a/docs/dev/style.md
+++ b/docs/dev/style.md
@@ -421,12 +421,44 @@ fn frobnicate(s: &str) {
421**Rationale:** reveals the costs. 421**Rationale:** reveals the costs.
422It is also more efficient when the caller already owns the allocation. 422It is also more efficient when the caller already owns the allocation.
423 423
424## Collection types 424## Collection Types
425 425
426Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`. 426Prefer `rustc_hash::FxHashMap` and `rustc_hash::FxHashSet` instead of the ones in `std::collections`.
427 427
428**Rationale:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount. 428**Rationale:** they use a hasher that's significantly faster and using them consistently will reduce code size by some small amount.
429 429
430## Avoid Intermediate Collections
431
432When writing a recursive function to compute a sets of things, use an accumulator parameter instead of returning a fresh collection.
433Accumulator goes first in the list of arguments.
434
435```rust
436// GOOD
437pub fn reachable_nodes(node: Node) -> FxHashSet<Node> {
438 let mut res = FxHashSet::default();
439 go(&mut res, node);
440 res
441}
442fn go(acc: &mut FxHashSet<Node>, node: Node) {
443 acc.insert(node);
444 for n in node.neighbors() {
445 go(acc, n);
446 }
447}
448
449// BAD
450pub fn reachable_nodes(node: Node) -> FxHashSet<Node> {
451 let mut res = FxHashSet::default();
452 res.insert(node);
453 for n in node.neighbors() {
454 res.extend(reachable_nodes(n));
455 }
456 res
457}
458```
459
460**Rational:** re-use allocations, accumulator style is more concise for complex cases.
461
430# Style 462# Style
431 463
432## Order of Imports 464## Order of Imports