Skip to content

Commit 4123f80

Browse files
committed
Use Vec::with_capacity(1) in a couple of places.
Because Vec::new() + push() results in a capacity of 4, and these particular vectors almost never grow past a length of 1. This change reduces the number of bytes of heap allocation significantly. (For serde it's a 15% reduction for a debug build.) This didn't give noticeable speed-ups on my machine but it's a trivial change and certainly can't hurt.
1 parent 6fc409e commit 4123f80

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

src/librustc/middle/dataflow.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ fn build_local_id_to_index(body: Option<&hir::Body>,
181181

182182
cfg.graph.each_node(|node_idx, node| {
183183
if let cfg::CFGNodeData::AST(id) = node.data {
184-
index.entry(id).or_insert(vec![]).push(node_idx);
184+
index.entry(id).or_insert_with(|| Vec::with_capacity(1)).push(node_idx);
185185
}
186186
true
187187
});
@@ -209,7 +209,8 @@ fn build_local_id_to_index(body: Option<&hir::Body>,
209209
}
210210

211211
fn visit_pat(&mut self, p: &hir::Pat) {
212-
self.index.entry(p.hir_id.local_id).or_insert(vec![]).push(self.entry);
212+
self.index.entry(p.hir_id.local_id)
213+
.or_insert_with(|| Vec::with_capacity(1)).push(self.entry);
213214
intravisit::walk_pat(self, p)
214215
}
215216
}

src/librustc/traits/project.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,11 @@ fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>(
597597
// can ignore the `obligations` from that point on.
598598
if !infcx.any_unresolved_type_vars(&ty.value) {
599599
infcx.projection_cache.borrow_mut().complete(cache_key);
600-
ty.obligations = vec![];
600+
// Use with_capacity(1) because
601+
// push_paranoid_cache_value_obligation() will push one
602+
// element, and then usually no more elements are pushed.
603+
// (Vec::new() + push() gives a capacity of 4.)
604+
ty.obligations = Vec::with_capacity(1);
601605
}
602606

603607
push_paranoid_cache_value_obligation(infcx,

0 commit comments

Comments
 (0)