Edit: These tests were run in Google Chrome back in September 2021 and not in NodeJS.
It's interesting to see some of the responses here. If you're not worried about legacy browser support (IE6+), skip on down to the interpolation method because it is extremely performant.
One of the most backwards compatible (back to IE6), and still very performant ways to duplicate a string by value is to split it into a new array and immediately rejoin that new array as a string:
let str = 'abc';
let copiedStr = str.split('').join('');
console.log('copiedStr', copiedStr);
Behind the scenes
What the above does is calls on JavaScript to split the string using no character as a separator, which splits each individual character into its own element in the newly created array. This means that, for a brief moment, the copiedStr
variables looks like this:
['a', 'b', 'c']
Then, immediately, the copiedStr
variable is rejoined using no character as a separator in between each element, which means that each element in the newly created array is pushed back into a brand new string, effectively copying the string.
At the end of the execution, copiedStr
is its own variable, which outputs to the console:
abc
Performance
On average, this takes around 0.007 ms - 0.01 ms on my machine, but your mileage may vary. Tested on a string wth 4,000 characters, this method produced a max of 0.2 ms and average of about .14 ms to copy a string, so it still has a solid performance.
Who cares about Legacy support anyways?/Interpolation Method
But, if you're not worried about legacy browser support, however, the interpolation
method offered in one of the answers on here, by Pirijan, is a very performant and easy to copy a string:
let str = 'abc';
let copiedStr = `${str}`;
Testing the performance of interpolation
on the same 4,000 character length string, I saw an average of 0.004 ms, with a max of 0.1 ms and a min of an astonishing 0.001 ms (quite frequently).
"" + slice
does not seem to work, nor does"" + slice + ""
. Trying other approaches. – Mattah.substr()
,.substring()
,.slice()
, and the relevant regex functions all return a new string. Is the other code that callsmyClass.myFunc()
keeping a reference to your huge string? If your real code is more complex, is it accidentally keeping the huge strings around in closures? – Sallyslice.reverse().reverse()
? If that also fails to resolve the behavior then I'm more likely to side with nnnnnn on the cause being something else. – Deadpan(' ' + src).slice(1)
. There is no official resolution. – Deadpan