diff --git a/.jules/bolt.md b/.jules/bolt.md index 5e43570..3326a5b 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -1,3 +1,7 @@ ## 2024-05-24 - Avoid vec! for constant collections in initialization loops **Learning:** Initializing maps/operator managers by iterating over `vec![...]` causes unnecessary heap allocations. Using array literals `[...]` is significantly more efficient since the size is known at compile time and the arrays can be stack-allocated or embedded directly into the binary. **Action:** Always prefer iterating over array literals instead of `vec![...]` for statically known collections, especially in hot paths or initialization loops. + +## 2024-05-24 - [Format Display Optimizations] +**Learning:** For `std::fmt::Display` implementations involving collections (like Lists or Maps), building an intermediate `String` via `format!()` and `push_str()` creates unnecessary heap allocations and redundant cloning. Writing directly to the formatter using `write!(f, ...)` avoids intermediate `String` allocations entirely. +**Action:** Always write directly to the `std::fmt::Formatter` inside `fmt` methods rather than creating an intermediate string representation, particularly when dealing with container-like structures. diff --git a/src/value.rs b/src/value.rs index b4c3384..f07feff 100644 --- a/src/value.rs +++ b/src/value.rs @@ -17,25 +17,22 @@ pub enum Value { impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::String(val) => write!(f, "value string: {}", val.clone()), - Self::Number(val) => write!(f, "value number: {}", val.clone()), - Self::Bool(val) => write!(f, "value bool: {}", val.clone()), + Self::String(val) => write!(f, "value string: {}", val), + Self::Number(val) => write!(f, "value number: {}", val), + Self::Bool(val) => write!(f, "value bool: {}", val), Self::List(values) => { - let mut s = String::from("["); + write!(f, "value list: [")?; for value in values { - s.push_str(format!("{},", value.clone()).as_str()); + write!(f, "{},", value)?; } - s.push_str("]"); - write!(f, "value list: {}", s) + write!(f, "]") } Self::Map(m) => { - let mut s = String::from("{"); + write!(f, "value map: {{")?; for (k, v) in m { - s.push_str(format!("key: {},", k.clone()).as_str()); - s.push_str(format!("value: {}; ", v.clone()).as_str()); + write!(f, "key: {},value: {}; ", k, v)?; } - s.push_str("}"); - write!(f, "value map: {}", s) + write!(f, "}}") } Self::None => write!(f, "None"), }