split/join vs regex replace (v20)

Revision 20 of this benchmark created on


Preparation HTML

<script>
  var str = '<div class="myclass"> beta/xyz </div>' + "<div class='new'> lambda munu xi omicron theta </div>",
      replacewith = {
      '<': '&#60;',
      '>': '&#62;',
      '"': '&#34;',
      "'": '&#39;',
      '/': '&#x2F;'
      };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
split/join
str.split('<').join('&#60;').split('>').join('&#62;').split("'").join('&#39;').split('"').join('&#34;').split('/').join('&#x2F;');
ready
regex replace
str.replace(/<|>|'|"|\//g, function(a) {
  switch (a) {
  case '<':return '&#60;';
  case '>':return '&#62;';
  case '"':return '&#34;';
  case "'":return '&#39;';
  case "/":return '&#x2F;';
  }
});
ready
regex replace 2
str.replace(/<|>|'|"|\//g, function(a) {
  return replacewith[a];
});
ready
replace 2
str.replace(/[<>'"\/]/g, function(a) {
  switch (a) {
  case '<':return '&#60;';
  case '>':return '&#62;';
  case '"':return '&#34;';
  case "'":return '&#39;';
  case "/":return '&#x2F;';
  }
});
ready
all replace
str
    .replace(/>/g, '&#62;')
    .replace(/</g, '&#60;')
    .replace(/"/g, '&#34;')
    .replace(/'/g, '&#39;')
    .replace(/\//g, '&#47;')
ready
replace 3
str.replace(/[<>'"\/]/g, function(a) {
  return replacewith[a];
});
ready

Revisions

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