Skip to content

benchmark: reduce string concatenations

Checklist
Affected core subsystem(s)

benchmark

I. Presupposition

String concatenations usually increase syntax noise and add confusion (a reader often has to check if string concatenation or number addition is intended). Moreover, it seems this method is not optimal performance-wise.

II. Cases

This PR aims two cases of string concatenation:

  • multipart concatenations with variable interpolation ('a' + b + 'c');
  • type coercion to String ('' + notString). This approach, while idiomatic, is not most declarative.

III. Performance

The added benchmark compares these variants:

  • 'a' + b + 'c' vs ['a', b, 'c'].join('') vs `a${b}c`
  • String(notString) vs '' + notString vs `${notString}`

Results with Node.js 8.0.0 rc:

es\string-concatenations.js mode="multi-concat"       n=1000:   909,455.5180758832
es\string-concatenations.js mode="multi-join"         n=1000:   290,896.9895943238
es\string-concatenations.js mode="multi-template"     n=1000: 2,620,236.0832711025

es\string-concatenations.js mode="to-string-string"   n=1000: 6,020,179.642160523
es\string-concatenations.js mode="to-string-concat"   n=1000: 1,141,656.7723079734
es\string-concatenations.js mode="to-string-template" n=1000: 5,700,376.794906143

IV. Commits

  1. Reduce string concatenations: replace concatenations with template literals, rewrap, String.prototype.repeat(), String(). Some replacements do not add indisputable readability gain, but I tried to be consistent.

  2. Add a benchmark for string concatenations vs counterparts.

  3. This commit is added here to avoid PR race condition and merge conflicts. It fixes an URL in _http-benchmarkers.js (removes duplicate hash symbol).

  4. This commit is added here to avoid PR race condition and merge conflicts. It fixes an evident typo in _http-benchmarkers.js: Error() constructor has only one parameter, while callback() has 5 (compare a previous call and callback() signature).

All changed files were minimally tested. CI for linting and new tests concerning benchmarks will be launched.

Merge request reports

Loading