Prompt
Be deliberate about memory allocation patterns to improve performance. Implement these practices:
- Pre-allocate collections when the size is known:
// Less efficient - may require multiple reallocations let mut output = Vec::new(); // More efficient - single allocation of correct size let mut output = Vec::with_capacity(self.len()); - Avoid unnecessary buffer clearing:
// Less efficient - discards existing content buffer.clear(); buffer.extend(new_items); // More efficient - preserves existing content when appropriate buffer.extend(new_items); - Use compact memory representations when appropriate:
// Less memory-efficient name: Option<Vec<u8>>, name_demangled: Option<String>, // More memory-efficient name: Option<Box<[u8]>>, name_demangled: Option<Box<str>>, - Defer allocation until needed:
// Less efficient - always reserves space buffer.reserve(BLOCK_CAP); // More efficient - only reserves when necessary if buffer.len() == buffer.capacity() { buffer.reserve(BLOCK_CAP); } - Be mindful of struct size and field initialization: Only store fields directly in structs when they’re always needed. Consider storing rarely used fields behind indirection (e.g., in an Option or Box) or restructuring to avoid initializing fields that aren’t always required.
These practices reduce memory pressure, improve cache locality, and minimize the overhead of memory management operations.