Skip to content
Draft
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
Expand Up @@ -41,3 +41,6 @@
## 2024-05-15 - Fast cache keys using integer math
**Learning:** Calling `new Date().toISOString().slice()` in hot paths (like `cached()` key generation during a backtest loop) adds up significantly (~1ms per thousand calls).
**Action:** When grouping cache keys by day, use fast integer math `Math.floor(unixSecs / 86400)` instead of string-based date allocations to maintain identical semantics while avoiding object instantiation.
## 2024-05-20 - Fast O(log n) lookups for day boundaries in time-series arrays
**Learning:** `lastSessionOnly` in `web/server/index.ts` previously used a chained `bars.filter` with `new Date(b.time * 1000).toISOString().slice(0, 10)` to keep only the bars from the last calendar day. This resulted in O(N) array traversal with extremely heavy Date and String allocations for every bar, causing significant performance overhead on large historical ranges.
**Action:** Replace `Date` and `toISOString()` string allocations with fast integer math (`Math.floor(time / 86400) * 86400`) to find the UTC day boundary in seconds. Since the time-series arrays are chronologically sorted, use O(log n) binary search (`findFirstBarIndex`) to locate the first matching bar and `.slice()` the rest, completely eliminating the allocation bottleneck.
8 changes: 6 additions & 2 deletions web/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { getDb } from "../../src/storage/db.js";
import {
getStockOhlcv,
getIndexOhlcv,
findFirstBarIndex,
type Bar,
type Resolution,
} from "../../src/data/sources/dnsePublic.js";
Expand Down Expand Up @@ -272,8 +273,11 @@ function rangeToPlan(range: RangeKey): { resolution: Resolution; fromSec: number
/** For a 1D range, keep only bars from the latest calendar day present. */
function lastSessionOnly(bars: Bar[]): Bar[] {
if (!bars.length) return bars;
const lastDay = new Date(bars[bars.length - 1]!.time * 1000).toISOString().slice(0, 10);
return bars.filter((b) => new Date(b.time * 1000).toISOString().slice(0, 10) === lastDay);
// Use O(log n) binary search on chronologically sorted time-series arrays
// rather than an O(n) array filter with string date allocations.
const lastDayStartSec = Math.floor(bars[bars.length - 1]!.time / 86400) * 86400;
const idx = findFirstBarIndex(bars, lastDayStartSec);
return idx === -1 ? bars : bars.slice(idx);
}

// ---------------------------------------------------------------------------
Expand Down
Loading