Skip to content

Inline ms.humanize for small diffs — avoid function call for sub-second deltas #48

@alanzabihi

Description

@alanzabihi

Hypothesis

The enabled path calls module.exports.humanize(this.diff) on every enabled call (node.js:176). The ms library's humanize function does a chain of comparisons (days, hours, minutes, seconds, ms) and string concatenation. For rapid debug calls, diff is almost always 0ms or a small number < 1000. Inlining the sub-second case (just `diff + 'ms'`) avoids the function call overhead and the ms library's comparison chain entirely.

Rationale

In the benchmark, 200K enabled calls execute in ~105ms. Each call computes diff = curr - prevTime. After warmup, most diffs are 0 or very small. The ms library's humanize function (ms@2.1.3) does: if >= day, if >= hour, if >= minute, if >= second, then return ms + 'ms'. For sub-second values, it traverses 4 comparisons before hitting the ms branch. A direct check `diff < 1000 ? diff + 'ms' : humanize(diff)` skips all of this.

Additionally, `module.exports.humanize` is a double property lookup per call. Caching the humanize reference in a local variable at module scope eliminates this.

Scope

  • src/node.js formatArgs(): add inline fast-path for diff < 1000 before falling back to humanize()
  • src/node.js top-level: cache humanize reference in a module-scope variable

Expected impact

Small to moderate. Eliminates function call + 4 comparisons for the common case. Combined with cached reference, removes 2 property lookups per call.

Risks

Must produce identical output. ms library returns e.g. '0ms', '5ms' for small values — our inline must match exactly. Only safe for values where ms returns `n + 'ms'` (i.e., diff < 1000 and diff >= 0).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions