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-05-15 - [Avoid dict.setdefault in hot loops with complex defaults]
**Learning:** `dict.setdefault(key, complex_default)` eagerly evaluates the default value even when the key exists. In hot loops, especially with dictionary/list comprehensions or complex object creation as the default value, this introduces measurable overhead.
**Action:** Replace `dict.setdefault(key, complex_default)` with an explicit `if key not in dict: dict[key] = complex_default` followed by `bucket = dict[key]` in performance-critical loops.
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 @@ -204,11 +203,11 @@ def _rebuild_if_needed(self) -> None:
aggregates: dict[tuple[Fraction, Fraction], dict[str, object]] = {}
total_value_sum = [Fraction(0) for _ in range(self._value_width or 0)]

# ⚑ Bolt Optimization: Avoid eager evaluation of complex defaults in hot loop
for index, (key, value) in enumerate(self._entries):
bucket = aggregates.setdefault(
key,
{"value_sum": [Fraction(0) for _ in value], "count": 0, "entry_indices": []},
)
if key not in aggregates:
aggregates[key] = {"value_sum": [Fraction(0) for _ in value], "count": 0, "entry_indices": []}
bucket = aggregates[key]
Comment on lines +206 to +210

Copilot AI Apr 9, 2026

Copy link

Choose a reason for hiding this comment

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

This does two dict lookups per iteration (key not in aggregates then aggregates[key]). Since this is a hot loop, consider a single-lookup approach (e.g., try/except KeyError or bucket = aggregates.get(key) with initialization) to avoid the extra hash-table probe when the key already exists.

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