Skip to content

perf: avoid cloning env during expansion - #149

Closed
chenjiahan wants to merge 2 commits into
dotenvx:masterfrom
chenjiahan:chenjiahan/perf-lazy-env-lookup
Closed

chenjiahan wants to merge 2 commits into
dotenvx:masterfrom
chenjiahan:chenjiahan/perf-lazy-env-lookup

Conversation

@chenjiahan

Copy link
Copy Markdown

Performance issue

expandValue currently creates a merged env object for every parsed .env key:

const env = { ...runningParsed, ...processEnv }

This means each key expansion clones the full processEnv object. In large projects, processEnv can contain thousands of keys, so loading a .env file with many entries repeatedly pays this cloning cost.

Optimization

This PR avoids cloning the full env object during each expandValue call.

Instead, it looks up env values lazily only when an expansion expression references a key.

Benchmark

Local benchmark with:

  • 2,000 processEnv keys
  • 200 parsed .env keys
  • 10 runs
Version Avg Min Max
Current 50.581 ms 49.217 ms 54.207 ms
Optimized 0.101 ms 0.061 ms 0.269 ms

Average speedup: ~498.6x.

@motdotla

Copy link
Copy Markdown
Collaborator

hi @chenjiahan - thank you for this. i've moved internals to use the new smarter @dotenvx/primitives though..

new major release coming out and then can reconsider a PR like this.

@motdotla motdotla closed this Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants