Array.join vs Template strings vs String concatenation
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.