Vec of Box adding a needless indirection
ID |
rust.performance.vec_box |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Rust |
Description
A Vec already stores its elements on the heap, so boxing each sized element allocates once per item and costs an extra pointer hop on every access, with no benefit. Store the values directly as Vec<T>. Boxing is still needed for trait objects and other unsized elements.
Rationale
A Vec already stores its elements on the heap, so boxing each sized element allocates once per item and costs an extra pointer hop on every access, with no benefit. Store the values directly as Vec<T>. Boxing is still needed for trait objects and other unsized elements.
The following code illustrates the pattern detected by this rule:
use std::error::Error;
struct Node {
v: u32,
}
// FLAGGED: Vec of Box adding a needless indirection
fn collect_nodes(nodes: Vec<Box<Node>>) -> usize {
nodes.len()
}