Skip to content

Cache ms.humanize result for identical consecutive diffs #12

@alanzabihi

Description

@alanzabihi

Hypothesis

ms.humanize(this.diff) is called on every enabled log (node.js line 176). When many calls happen in rapid succession (typical in batch logging), the diff is often 0ms repeatedly. Caching the humanize result when the diff matches the previous call avoids redundant ms library invocations.

Rationale

In the benchmark, 50K iterations run as fast as possible. Most calls have diff=0 or diff=very small, producing the same humanized string (e.g. '+0ms'). Caching with a simple previous-diff/previous-result pair avoids calling into the ms library for repeated identical inputs.

The cache is per-instance (stored on the debug function) so different instances do not interfere.

Scope

  • src/node.js formatArgs() line 176: add diff-based cache for humanize result
  • Alternatively, cache in common.js before calling formatArgs

Expected impact

Moderate. ms.humanize does number comparisons and string concatenation. Skipping it for repeated diffs saves ~200K function calls and string allocations per benchmark run.

Risks

Must invalidate correctly when diff changes. A simple if (diff === lastDiff) return cachedResult pattern is sufficient. No risk of stale data since diff is computed fresh each call.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions