P粉2447306252023-08-28 15:08:49
I'm disappointed that no one in the other answers explained "best way" to mean "fastest way"...
I extracted two examples from here and added str. join()
and str.reduce()
from nishanths' answer above. Here are my results on Firefox 77.0.1 on Linux.
Note: I discovered while testing these that if I put str = str.concat()
and str =
directly before or after each other Between them, the second one always performs better... so I run these tests individually and comment on the results of the other tests...
Even so, their speeds would change a lot if I reran them, so I measured each 3 times.
1 character at a time:
str = str.concat()
: 841, 439, 956 ms / 1e7
............str =
:949, 1130, 664 milliseconds / 1e7 ='s
......[].join()
: There are 3350, 2911, 3522 ms / 1e7 characters in []
...[].reduce()
: 3954, 4228, 4547 ms / 1e7 characters in []
26 strings at a time:
str = str.concat()
: 444, 744, 479 ms / 1e7
............str =
:1037, 473, 875 milliseconds / 1e7 ='s
........[].join()
: 2693, 3394, 3457 ms / 1e7 string in []
......[].reduce()
: 2782, 2770, 4520 ms / 1e7 string in []
So, whether appending 1 character at a time or appending 26 strings at a time:
str = str.concat()
and str =
[].reduce()
, then [].join()
My code, easy to run in browser console:
{ console.clear(); let concatMe = 'a'; //let concatMe = 'abcdefghijklmnopqrstuvwxyz'; //[].join() { s = performance.now(); let str = '', sArr = []; for (let i = 1e7; i > 0; --i) { sArr[i] = concatMe; } str = sArr.join(''); e = performance.now(); console.log(e - s); console.log('[].join(): ' + str); } //str += { s = performance.now(); let str = ''; for (let i = 1e7; i > 0; --i) { str += concatMe; } e = performance.now(); console.log(e - s); console.log('str +=: ' + str); } //[].reduce() { s = performance.now(); let str = '', sArr = []; for (let i = 1e7; i > 0; --i) { sArr[i] = concatMe; } str = sArr.reduce(function(pre, next) { return pre + next; }); e = performance.now(); console.log(e - s); console.log('[].reduce(): ' + str); } //str = str.concat() { s = performance.now(); let str = ''; for (let i = 1e7; i > 0; --i) { str = str.concat(concatMe); } e = performance.now(); console.log(e - s); console.log('str = str.concat(): ' + str); } 'Done'; }
P粉4125335252023-08-28 14:12:16
Using ES6, you can use
Template string: p>
var username = 'craig'; console.log(`hello ${username}`);
ES5 and below:
Using
Operator
var username = 'craig'; var joined = 'hello ' + username;
String concat (..)
var username = 'craig'; var joined = 'hello '.concat(username);
Or, use the array method:
var username = 'craig'; var joined = ['hello', username].join(' ');
Or more exotically, < code>reduce(..) combined with any of the above:
var a = ['hello', 'world', 'and', 'the', 'milky', 'way']; var b = a.reduce(function(pre, next) { return pre + ' ' + next; }); console.log(b); // hello world and the milky way