Skip to content

Commit 09f9f73

Browse files
perf: optimize Display for Value List and Map
Refactor fmt::Display implementation for Value::List and Value::Map to write directly to the formatter. This avoids unnecessary String allocations, format! macro calls, and value cloning. Co-authored-by: ashyanSpada <22587148+ashyanSpada@users.noreply.github.com>
1 parent 9a4a6cc commit 09f9f73

1 file changed

Lines changed: 8 additions & 9 deletions

File tree

src/value.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,21 +21,20 @@ impl fmt::Display for Value {
2121
Self::Number(val) => write!(f, "value number: {}", val.clone()),
2222
Self::Bool(val) => write!(f, "value bool: {}", val.clone()),
2323
Self::List(values) => {
24-
let mut s = String::from("[");
24+
// ⚡ Bolt: Write directly to the Formatter to prevent N+1 heap allocations and deep copies.
25+
write!(f, "value list: [")?;
2526
for value in values {
26-
s.push_str(format!("{},", value.clone()).as_str());
27+
write!(f, "{},", value)?;
2728
}
28-
s.push_str("]");
29-
write!(f, "value list: {}", s)
29+
write!(f, "]")
3030
}
3131
Self::Map(m) => {
32-
let mut s = String::from("{");
32+
// ⚡ Bolt: Avoid intermediate String allocations and push_str() by writing directly to the output stream.
33+
write!(f, "value map: {{")?;
3334
for (k, v) in m {
34-
s.push_str(format!("key: {},", k.clone()).as_str());
35-
s.push_str(format!("value: {}; ", v.clone()).as_str());
35+
write!(f, "key: {},value: {}; ", k, v)?;
3636
}
37-
s.push_str("}");
38-
write!(f, "value map: {}", s)
37+
write!(f, "}}")
3938
}
4039
Self::None => write!(f, "None"),
4140
}

0 commit comments

Comments
 (0)