re: How to reverse a string in JavaScript VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION
 

Here is an test that reverses 100 different strings with length 200000 (±6):

const base = require('crypto').randomBytes(2e5).toString();
const m0 = process.memoryUsage().rss;
const t0 = process.hrtime();
const arr = [];
for (let i = 0; i < 100; i++) {
  const str = `${i}${base}${i}`;
  const reversed = str.split('').reverse().join(''); // +103 MiB, 3.7 seconds
  //const reversed = [...str].reverse().join(''); // +118 MiB, 3.9 seconds
  //const reversed = [...str].reduce((prev,next)=>next+prev); // +1080 MiB, 6.0 seconds
  //const reversed = reverseString(str); // +1105 MiB, 6.5 seconds
  arr.push(reversed);
}
const t1 = process.hrtime(t0);
const m1 = process.memoryUsage().rss;
console.log((m1 - m0) / 2**20, t1[0] + t1[1] * 1e-9);

Note that unlike a very simple microbench, it actually retains those strings (i.e. puts the results into an array), which is a bit closer to what you might see in actual application.

The first method consumes 103 MiB.

The char-by-char concat methods consume over 1 GiB, and are slower.
Also, longer and less readable.


Bonus: try replacing 100 with 200 (the number of strigs in the for loop).

split/reverse/join consumes 170 MiB and 7 seconds.

The last two (reduce and «reverseString») die with OOM after 19 seconds.


That is also valid for shorter strings, e.g. try with 10000 (and 50000) of strings with length = 1000.

10000 iterations, 1000 length = 50 MiB / 1 second vs 520 MiB / 2 seconds.
50000 iterations, 1000 length = 129 MiB / 5 seconds vs OOM / 14 seconds.

code of conduct - report abuse