new String replaceAll Javascript not so powerful

There’s a new javascript function in the String prototype, called replaceAll.

We all tried the native replace function, to find that it only replace the first occurrence, and we have to use a regex to really replace all, like this:
“the blue fox”.replace(/blue/g, “red”);

Now, the replaceAll does what we hope, by replacing all “string1” with “string2”, in the whole string instance, returning a copy of it.

But, in the meantime, lots of people tried to create their own replaceAll function, and one of them was to use the split / join trick. We found that it’s also very powerful when we need to manage large strings, or with a large amount of strings to convert.

So, I tried to see if I can replace all my split-join usage, with the new replaceAll.
And, the answer is NO!
Instead, I will make sure I never use the new replaceall, and I’ll keep my old custom function.

The split-join is, depending on the length of the input / find / replaceBy variables, up to 5 times faster in the tests I did.
Sometimes, it’s the same speed, but most of the time, it’s faster. And, in Chrome 85, it’s never slower.

Test code:

    <button onclick="test_replaceAll();">replaceAll</button>
    <button onclick="test_split();">split</button>
    <script>
      console.clear()
      var i = 25;
      var s = "asdf".repeat(i * 100000);
      var sFrom = "sd";
      var sTo = "z".repeat(i);

      function test_replaceAll(){
        var t0 = (new Date()).getTime();
        var t1 = s.replaceAll(sFrom, sTo);
        console.log("t1", t1.length, (new Date()).getTime() - t0);
      }

      function test_split(){
        var t0 = (new Date()).getTime();
        var t2 = s.split(sFrom).join(sTo);
        console.log("t2", t2.length, (new Date()).getTime() - t0);
      }
    </script>

Look at these results: First 5 are “replace”, last 5 are “split/join”

replaceAll: 750ms
split/join: 250ms

There’s no doubt that the split/join method is still the fastest.

But, if you need to use “regex” instead, now the replaceAll is the one to use.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.