Skip to content

Replace split/join multiline with String.replace regex in formatArgs #49

@alanzabihi

Description

@alanzabihi

Hypothesis

formatArgs (node.js) does args[0].split('\n').join('\n' + prefix) for multiline handling. Replacing with args[0].replace(/\n/g, '\n' + prefix) avoids array allocation and handles single-line messages efficiently.

Rationale

The benchmark exercises 4 call types. Only the multiline call has newlines, but split/join runs on all 4. For 3 single-line calls (75%), split creates a 1-element array and join returns it unchanged — pure overhead. String.replace with /\n/g is faster: no array allocation, V8 short-circuits no-match replace.

Note: the current main already has an indexOf('\n') guard, so split/join only runs on actual multiline messages. This thesis targets replacing split/join with regex replace within that guarded branch to further reduce overhead when multiline messages do occur.

Scope

  • src/node.js formatArgs(): replace split('\n').join('\n' + prefix) with replace(/\n/g, '\n' + prefix) inside the multiline branch

Expected impact

Small. The indexOf guard already skips single-line messages. This only helps the multiline case (25% of bench calls).

Risks

Must produce byte-identical output. The regex /\n/g replaces each \n with \n+prefix, semantically identical to split/join.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions