Skip to content
jshacks.dev
Performance

Why string concatenation is fast in V8

V8 stores a concatenated string as a rope that points at its parts, so += in a loop is cheap until you read the result, which flattens it once.

1 min read
Summarize in AI

Strings are immutable, so you might expect += in a loop to copy the whole string each time. V8 avoids that.

concat.jsJavaScript
let html = '';
for (let i = 0; i < 5; i++) {
  html += `<li>${i}</li>`;
}
console.log(html);

const parts = [];
for (let i = 0; i < 5; i++) parts.push(`<li>${i}</li>`);
console.log(parts.join('') === html);
Text
<li>0</li><li>1</li><li>2</li><li>3</li><li>4</li>
true

When two strings are joined and the result is long enough, V8 creates a "cons string" (a rope): a small node holding pointers to the left and right parts, instead of a fresh copy. Many += calls build a tree of such nodes cheaply. The tree is flattened into one contiguous string only when something needs to read it, such as indexing, a regex or a comparison.

So += is a fine default, and the old advice to always collect pieces in an array and join is not needed for performance in V8. An array and join is still clear when you build from many separate steps. Avoid reading the string in the middle of the loop, for example html.length is fine but html[i] forces a flatten each pass. See the addition assignment operator.

Taggedv8
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.