indexOf replaceAll versus Regexp

Benchmark created by sevifives on


Description

testing a replace all that doesn't use regex

Setup

String.prototype.replaceAll = function (needle, rep, strictMatch) {
      var haystack = this, idx, len, needleE, needleR, ret;
    
      if (haystack.length === 0) { return haystack; }
    
      needleE = needle.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    
      needleR = new RegExp(needleE, strictMatch?'':'i');
    
      ret = haystack.split(needleR).join(rep);
    
      return ret;
    };
    
    var testString = "";
    for (i=0;i<1000;i++) {
      testString += "a test and crushing defeat ";
      if (i%3===0) {testString += "bees suck ";}
    }
    var upTest = testString.toUpperCase();

Test runner

Ready to run.

Testing in
TestOps/sec
replaceAll insensitive
var results = upTest.replaceAll('bees suck', 'but are cool');
ready
RegExp replace all insensitive
var results = upTest.replace(/bees suck/gi,'but are cool')
ready
replaceAll case sensitive
var results = testString.replaceAll('bees suck', 'but are cool',true);
ready
Regexp strict match replace
var results = testString.replace(/bees suck/g,'but are cool')
ready

Revisions

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

  • Revision 1: published by sevifives on