Skip to content

[BUG] valid function is creating a new SemVer object and immediately destroying it #544

Closed
@rvbsm

Description

@rvbsm

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

Original author: https://marvinh.dev/blog/speeding-up-javascript-ecosystem/

parse returns a new SemVer or null object, which is only used to verify that the supplied version string can be considered SemVer:

const valid = (version, options) => {
  const v = parse(version, options)
  return v ? v.version : null
}

That is a huge job for GC because the SemVer is created and destroyed every time function called

Expected Behavior

Verify that provided version string is valid SemVer without creating a new object.

E.g. copy some code from SemVer constructor:

const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { re, t } = require('../internal/re')
const parseOptions = require('../internal/parse-options')

const valid = (version, options) => {
  options = parseOptions(options);
  
  if (typeof version !== "string") {
    return false;
  }
  
  if (version.length > MAX_LENGTH) {
    return false;
  }
  
  const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])

  if (!m) {
    return false;
  }

  const major = +m[1]
  const minor = +m[2]
  const patch = +m[3]
  
  if (major > MAX_SAFE_INTEGER || major < 0) {
    return false
  }

  if (minor > MAX_SAFE_INTEGER || minor < 0) {
    return false
  }

  if (patch > MAX_SAFE_INTEGER || patch < 0) {
    return false
  }
  
  return true  
}

That's not perfect solution, but we get rid of unused SemVer objects

Steps To Reproduce

  1. Any environment
  2. Any config
  3. Run semver
  4. See slow config parsing

Environment

  • pnpm: 8.2.0
  • Node: 19.7.0
  • OS: Pop!_OS 22.04
  • platform: Ryzen 5 4600H, 16GB RAM

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bugthing that needs fixingNeeds Triageneeds an initial review

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions