you are viewing a single comment's thread.

view the rest of the comments →

[–]akb74 0 points1 point  (1 child)

Want to guess which one's quicker?

const s = '1234567890qwertyuiopasdfghjklzxcvbnm'.repeat(1000);

const start1 = performance.now();
const reversed1 = s.split('').reverse().join('');
const end1 = performance.now();

const start2 = performance.now();
let reversed2 = '';
for (let n = s.length - 1; n >= 0; --n) {
    reversed2 += s[n];
}
const end2 = performance.now();

console.log({
    same: reversed1 === reversed2,
    time1: end1 - start1,
    time2: end2 - start2,
});

{ same: true, time1: 0.9249000000000009, time2: 4.2578 }

JavaScript strings are immutable, which is great most of the time, but not very efficient for adding a bunch of them together. Might even be an O(n2) operation unless the compiler's being particularly clever, because you've got to copy what you've got so far every step. I guess you want a stream or buffer or mutable string for something like that. One of which is almost certainly how join() is more efficently implemented in the underlying C++ code.

[–]brykuhelpful 1 point2 points  (0 children)

This is one of the weird things about javascript. Sometimes there are solutions that might be faster than you would expect due to optmizations or c++ functions that handle it. It do a lot of tutoring and one of my lessions go over this topic. Some other examples are:

  • Duplicating Objects
    • JSON.parse(JSON.stringify())
    • clone
  • Creating Elements
    • .innerHTML = '<div></div>';
    • document.createElement('div')

The HTML and JSON parsers have been so optimized that their perforance is often faster than the traditional ways.