Languages

JavaScript - array join vs string concatenation performance

0 points
Asked by:
Evania
584

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
Answered by:
Evania
584

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

  1. JavaScript - test algorithm performance

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join