From f412976bdc46438ee80ee5f928e2572b2978ed06 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Fri, 24 Jul 2026 15:35:49 +0000 Subject: [PATCH] perf: replace O(n) array filter with O(log n) binary search in clipBars In tight loops during backtesting, calling clipBars which executes an O(n) array filter over large OHLCV bars array creates massive overhead. This optimizes clipBars by replacing array filter with the existing findLastBarIndex for O(log n) binary search on the chronologically sorted bars array. Co-authored-by: toreleon <42534763+toreleon@users.noreply.github.com> --- src/data/sources/dnsePublic.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/data/sources/dnsePublic.ts b/src/data/sources/dnsePublic.ts index ee39639..5347f20 100644 --- a/src/data/sources/dnsePublic.ts +++ b/src/data/sources/dnsePublic.ts @@ -88,7 +88,12 @@ function clipBars(bars: Bar[]): Bar[] { asOfClock.getStore()?.asOfSec != null || isAsOfOverridden(); if (!hasOverride) return bars; const asOf = nowSec(); - return bars.filter((b) => b.time <= asOf); + + // Performance: In tight backtest loops, filtering an O(N) array creates massive overhead. + // We use binary search since bars are chronologically sorted to make lookups O(log N). + const lastIdx = findLastBarIndex(bars, asOf); + if (lastIdx === -1) return []; + return bars.slice(0, lastIdx + 1); } export async function getStockOhlcv(