From c8a412df38d96ffe87dd50ed5a2a005616580182 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 14 May 2026 04:00:00 +0000 Subject: [PATCH] Optimize dictionary initialization with reduce(into:) Co-authored-by: acebytes <2820910+acebytes@users.noreply.github.com> --- .jules/bolt.md | 4 ++++ Sources/Cacheout/Intervention/Tier2Interventions.swift | 7 +++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.jules/bolt.md b/.jules/bolt.md index dd1b466..77fc240 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -21,3 +21,7 @@ ## 2026-03-19 - FileManager Enumerator Pre-fetching **Learning:** Any property requested via `resourceValues(forKeys:)` inside a `FileManager.enumerator` loop must also be in `includingPropertiesForKeys` — otherwise `URL.resourceValues` falls back to a synchronous `stat()` per file, turning bulk reads into O(N) disk I/O. **Action:** Keep the keys array passed to `resourceValues(forKeys:)` a subset of the prefetch list passed to `FileManager.enumerator(at:includingPropertiesForKeys:)`. + +## 2024-05-15 - Dictionary initialization performance with reduce(into:) +**Learning:** Standard `for` loop dictionary insertions in Swift can trigger repeated mutation and Copy-On-Write (COW) overhead. Standard `.map` implementations create intermediate array allocations. +**Action:** For efficient and safe initialization of dictionaries/index maps, use `reduce(into: [:])`. This avoids intermediate array allocations and prevents COW overhead by passing the accumulator as an `inout` reference. diff --git a/Sources/Cacheout/Intervention/Tier2Interventions.swift b/Sources/Cacheout/Intervention/Tier2Interventions.swift index 92c8c5a..02e5617 100644 --- a/Sources/Cacheout/Intervention/Tier2Interventions.swift +++ b/Sources/Cacheout/Intervention/Tier2Interventions.swift @@ -226,10 +226,9 @@ public final class JetsamHWM: Intervention { } // Step 3: Build priority lookup by PID (keep first entry per PID to avoid trap on duplicates). - var priorityByPID: [pid_t: JetsamPriorityEntryDTO] = [:] - for entry in priorities { - if priorityByPID[entry.pid] == nil { - priorityByPID[entry.pid] = entry + let priorityByPID = priorities.reduce(into: [pid_t: JetsamPriorityEntryDTO]()) { result, entry in + if result[entry.pid] == nil { + result[entry.pid] = entry } }