Array.join vs Template strings vs String concatenation

This article introduces the comparison between Array.join, Template strings, and String concatenation, including their advantages, implementation details, and related resources to improve efficiency.

Feb 28, 2021 · 2 min read · 297 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Recently I saw a question on Stack Overflow, Are ES6 template literals faster than Array join at constructing long strings. This question was directly closed by the moderators, so I couldn’t see anyone providing an answer. But the question is indeed interesting, since I wasn’t sure about the answer either, I decided to test it and record the results here.

Benchmark

The test data and code are as follows.

var arr = Array(10000)
  .fill(1)
  .map(() => 'A' + Math.ceil(Math.random() * 100));


// array.join
var res=arr.join('; ');

// string literal
var finalString2 = arr.reduce((res, item) => {
  return `${res}; ${item}`;
}, '');

// string concatenation
var finalString3 = arr.reduce((res, item) => {
  return res + '; ' + item;
}, '');

The test results are shown below. As you can see, array.join performs the best. I tried to change the sample data volume (the length of the array), but the results remained consistent.

Analysis

After some consideration, the reason why string literals and string concatenation consume more performance is that they both need to create temporary resource strings for assignment in the callback functions mentioned above. The difference between string literals and string concatenation is that with string literals, the callback only needs one temporary string, while string concatenation requires two (two “+” operations).

Conclusion

Indeed, sometimes performance doesn’t matter that much. After all, it’s easy for programmers to write code that computers can understand, but writing code that programmers can understand is harder. Sometimes we don’t need to worry about these small performance differences. However, when dealing with large volumes of data processing logic, we do need to consider this point, because the system could crash, right?

From this, at least we know that when dealing with larger data volumes, array.join still offers relatively the best performance.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover