EN
JavaScript - array join vs string concatenation performance
1
answers
0
points
Which method is faster array join()
or string concatenation using +=
operator?
For example:
1. Array join()
const array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var result = array.join('');
2. String concatenation using +=
const array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var result = '';
for (var i = 0; i < array.length; ++i) {
result += array[i];
}
1 answer
0
points
String concatenation using +=
operator is faster. Below I've prepared a performance test.
Performance test
// ONLINE-RUNNER:browser;
const test = (repeats, description, func) => {
const t1 = Date.now();
for (let i = 0; i < repeats; ++i) {
func();
}
const t2 = Date.now();
const dt = t2 - t1;
console.log(`${description}: totoal time is ${dt} ms`);
};
// Tested algorithms:
const joinString = (array) => array.join('');
const concatString = (array) => {
var result = '';
for (var i = 0; i < array.length; ++i) {
result += array[i];
}
return result;
};
// Input data:
const array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
// Performance tests:
const repeats = 10000; // set number of repeats depending on cases complexity
test(repeats, 'Using join()', () => joinString(array));
test(repeats, 'Using += operator', () => concatString(array));
See also
0 comments
Add comment