Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2024-03-24 - [Avoid eager evaluation of default dict in hot loops]
**Learning:** Found a specific bottleneck where `setdefault` was used inside a loop to instantiate complex default dicts with `Fraction` objects, causing high overhead. Eager evaluation of the default parameter inside `setdefault` happens on *every* loop iteration regardless of key presence.
**Action:** Replace `setdefault` with an explicit `if key not in dict:` check to instantiate expensive defaults lazily only when necessary. Also beware of local benchmark side effects dirtying `results/` folder tracked files.
9 changes: 4 additions & 5 deletions src/geometry/hull_kv.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
HardmaxResult,
NumberLike,
ValueLike,
_as_fraction,
_coerce_key,
_coerce_value,
_normalize_number,
Expand Down Expand Up @@ -205,10 +204,10 @@ def _rebuild_if_needed(self) -> None:
total_value_sum = [Fraction(0) for _ in range(self._value_width or 0)]

for index, (key, value) in enumerate(self._entries):
bucket = aggregates.setdefault(
key,
{"value_sum": [Fraction(0) for _ in value], "count": 0, "entry_indices": []},
)
# ⚑ OPTIMIZATION: Avoid eager evaluation of complex default dict on every iteration
if key not in aggregates:
aggregates[key] = {"value_sum": [Fraction(0) for _ in value], "count": 0, "entry_indices": []}
bucket = aggregates[key]
Comment on lines +207 to +210

Copilot AI Apr 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this hot loop, if key not in aggregates: ...; bucket = aggregates[key] performs two hash lookups per iteration (one for in, one for []). Since this code is explicitly performance-sensitive, consider using a single-lookup pattern (e.g., bucket = aggregates.get(key) and initialize on None, or a try/except KeyError) to keep the lazy default while avoiding the extra lookup on the common hit path.

Copilot uses AI. Check for mistakes.
for coord_index, coord in enumerate(value):
bucket["value_sum"][coord_index] += coord
total_value_sum[coord_index] += coord
Expand Down