replace.replace vs replace(a|b, callback) (v2)

Revision 2 of this benchmark created by osexp on


Description

replace.replace.replace... replace(a|b,callback) replace([ab],callback) split.map.join split.reduce

Setup

var result;
    var source = '';
    for (var i = 0; i < 1000; i++) {
      source += '............a.b.c.d............a.......b........cd'; //50bytes
    }

Test runner

Ready to run.

Testing in
TestOps/sec
replace.replace...
result = source.replace(/a/g, 'A').replace(/b/g, 'B').replace(/c/g, 'C').replace(/d/g, 'D')
ready
replace(/a|b/g, callback)
result = source.replace(/a|b|c|d/g, function(char) {
  return char === 'a' ? 'A' : char === 'b' ? 'B' : char === 'c' ? 'C' : char === 'd' ? 'D' : '?'
});
ready
replace(/[ab]/g, callback)
result = source.replace(/[abcd]/g, function(char) {
  return char === 'a' ? 'A' : char === 'b' ? 'B' : char === 'c' ? 'C' : char === 'd' ? 'D' : '?'
});
ready
split.map.join
result = source.split('').map(function(char) {
  return char === 'a' ? 'A' : char === 'b' ? 'B' : char === 'c' ? 'C' : char === 'd' ? 'D' : char
}).join('');
ready
split.reduce
result = source.split('').reduce(function(joinedStr, char) {
  return joinedStr + (char === 'a' ? 'A' : char === 'b' ? 'B' : char === 'c' ? 'C' : char === 'd' ? 'D' : char);
});
ready
replace(callback).replace(callback)
result = source.replace(/a/g, function() {
  return 'A'
}).replace(/b/g, function() {
  return 'B'
}).replace(/c/g, function() {
  return 'C'
}).replace(/d/g, function() {
  return 'D'
})
ready

Revisions

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

  • Revision 2: published by osexp on