indexOf vs replace

Benchmark created on


Description

string.replace() will return the string if it doesn't match. But the regex slows it down.

"Guarding" the replace with an indexOf check will be about 80% faster!

Setup

var name = 'bla'
var name2 = 'bla.2'
var fieldArrayIndex = -1
var fieldName = ''

Test runner

Ready to run.

Testing in
TestOps/sec
Without indexOf
fieldName = name.replace(/(.+)\.(\d+)/, (_match, g1, g2) => {
    fieldArrayIndex = Number(g2);
    return g1;
  });
ready
With indexOf
fieldName =
    name.indexOf('.') < 0
      ? name
      : name.replace(/(.+)\.(\d+)/, (_match, g1, g2) => {
          fieldArrayIndex = Number(g2);
          return g1;
        });
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.