Skip to content

Commit 22f3fc6

Browse files
committed
perf: Optimize insert_nested to eliminate unnecessary clone
Apply Copilot's review suggestion to use Entry API pattern instead of or_insert_with, eliminating an unnecessary clone of the key. Changes: - Use match on map.entry(key) instead of entry(key.clone()) - Handle Occupied and Vacant cases explicitly - Reduces allocations in recursive nested insertion All tests pass.
1 parent fbf764e commit 22f3fc6

1 file changed

Lines changed: 16 additions & 12 deletions

File tree

src/environment.rs

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -285,18 +285,22 @@ impl Environment {
285285

286286
// Recursive case: get or create the nested object
287287
let key = parts[0].to_string();
288-
let nested_map = map
289-
.entry(key.clone())
290-
.or_insert_with(|| Value::Object(Map::new()));
291-
292-
// If the entry exists but is not an object, replace it with an object
293-
if let Value::Object(ref mut nested) = nested_map {
294-
Self::insert_nested(nested, &parts[1..], value);
295-
} else {
296-
// Replace non-object with a new object containing the nested value
297-
let mut new_map = Map::new();
298-
Self::insert_nested(&mut new_map, &parts[1..], value);
299-
map.insert(key, Value::Object(new_map));
288+
match map.entry(key) {
289+
serde_json::map::Entry::Occupied(mut occ) => {
290+
if let Value::Object(ref mut nested) = occ.get_mut() {
291+
Self::insert_nested(nested, &parts[1..], value);
292+
} else {
293+
// Replace non-object with a new object containing the nested value
294+
let mut new_map = Map::new();
295+
Self::insert_nested(&mut new_map, &parts[1..], value);
296+
*occ.get_mut() = Value::Object(new_map);
297+
}
298+
}
299+
serde_json::map::Entry::Vacant(vac) => {
300+
let mut new_map = Map::new();
301+
Self::insert_nested(&mut new_map, &parts[1..], value);
302+
vac.insert(Value::Object(new_map));
303+
}
300304
}
301305
}
302306

0 commit comments

Comments
 (0)