From fa538a9f20db04b1fb3662d3ccd230a815195fdb Mon Sep 17 00:00:00 2001 From: mediumWellness Date: Tue, 4 Aug 2026 02:17:10 +1000 Subject: [PATCH] perf: cache loadConfig() and ensureConfigDir() results to eliminate repeated disk reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add module-level in-memory caches for both config loading and config-dir creation to avoid redundant synchronous fs operations on every CLI command invocation. - _configCache: VeniceConfig | null — populated on first loadConfig() call; returned directly on subsequent calls; updated by saveConfig() so it stays in sync after writes - _configDirEnsured: boolean — set to true after the first successful ensureConfigDir(); subsequent calls return immediately without an fs.existsSync() round-trip Before this change every output line triggered: getChalk() -> createChalk() -> isColorEnabled() -> loadConfig() -> fs.readFileSync() and each of getDefaultModel(), getDefaultImageModel(), getDefaultVoice(), getApiKey(), shouldShowUsage(), getOutputFormat() also called loadConfig() independently, causing N synchronous disk reads per invocation. After this change only the first call incurs any I/O. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/lib/config.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/lib/config.ts b/src/lib/config.ts index 442f559..86ec5c1 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -14,28 +14,38 @@ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json'); const HISTORY_FILE = path.join(CONFIG_DIR, 'history.json'); const USAGE_FILE = path.join(CONFIG_DIR, 'usage.json'); +let _configDirEnsured = false; + export function ensureConfigDir(): void { + if (_configDirEnsured) return; if (!fs.existsSync(CONFIG_DIR)) { fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); } + _configDirEnsured = true; } +let _configCache: VeniceConfig | null = null; + export function loadConfig(): VeniceConfig { + if (_configCache !== null) return _configCache; ensureConfigDir(); try { if (fs.existsSync(CONFIG_FILE)) { const content = fs.readFileSync(CONFIG_FILE, 'utf-8'); - return JSON.parse(content); + _configCache = JSON.parse(content); + return _configCache!; } } catch { // Return empty config on error } - return {}; + _configCache = {}; + return _configCache; } export function saveConfig(config: VeniceConfig): void { ensureConfigDir(); fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 }); + _configCache = config; // keep cache in sync } export function getConfigValue(key: keyof VeniceConfig): unknown {