feat: cache semver calls during dependency resolution #8545
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This blog post about the performance impact of
semver
on npm installations has been doing the rounds lately: https://marvinh.dev/blog/speeding-up-javascript-ecosystem-part-12/ Per discussion at npm/node-semver#800, there don't seem to be any low-hanging fruit optimizations insemver
itself.One part of the post that stood out to me is that npm frequently calls
semver
in a way that produces duplicative work. For instance, callingif (semver.valid(version))
followed bysemver.parse(version)
actually parses the version twice, becausesemver.valid
usessemver.parse
under the hood. (There's a built-in cache that prevents some of semver's work from being duplicated, but not all of it.) This could in principle be addressed insemver
this by memoizingsemver.parse
, but that would be a compatibility-breaking change because the object returned bysemver.parse
is mutable: If a consumer modified the object, that would affect anyone else who callssemver.parse
with the same version.With that in mind, this PR adds a
cached-semver
utility to npm. It's a drop-in replacement forsemver
that uses caching to ensure that versions and ranges are only parsed once. This should significantly speed up installs, updates, and audits.