String.link HTML Escapement

JavaScript performance comparison

Revision 3 of this test case created by Jason Miller

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var div = document.createElement('div');
    var properValue = "foo&lt;&gt;&#039;&quot;";
    var value;
   
    var stringLinkReg = /"(.*)"/gi;
    function stringDotLink(str) {
      stringLinkReg.lastIndex = 0;
      return stringLinkReg.exec(String.prototype.link(str))[1];
    }
   
    function divTextContent(str) {
      div.textContent = "foo<>'\"";
      return div.innerHTML.replace(/'/g,'&#039;').replace(/"/g,'&quot;');
    }
   
    function naiveReplacer(s) {
      if (s==='<') {
        return '&lt;';
      }
      if (s==='>') {
        return '&gt;';
      }
      if (s==="'") {
        return '&#039;';
      }
      if (s==='"') {
        return '&quot;';
      }
    }
    var map={ '<':'&lt;', '>':'&gt', "'":'&#039;', '"':'&quot;' };
    function mapReplacer(s) {
      return map[s] || s;
    }
    function regexpSingleNaive(str) {
      return str.replace(/[<>'"]/g, naiveReplacer);
    }
    function regexpSingleMap(str) {
      return str.replace(/[<>'"]/g, naiveReplacer);
    }
   
    function regexpMultiple(str) {
      return (str.replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/'/g, '&#039;')
        .replace(/"/g, '&quot;'));
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
String.prototype.link()
value = stringDotLink("foo<>'\"");
if (value!==properValue) {
  console.log(value, properValue);
  //throw("Incorrect: "+value+" !== "+properValue);
}
pending…
innerText<>innerHTML
value = divTextContent("foo<>'\"");
if (value!==properValue) {
  console.log(value, properValue);
  throw("Incorrect: "+value+" !== "+properValue);
}
pending…
RegExp (single, naive)
value = regexpSingleNaive("foo<>'\"");
if (value!==properValue) {
  console.log(value, properValue);
  throw("Incorrect: "+value+" !== "+properValue);
}
pending…
RegExp (single, map)
value = regexpSingleMap("foo<>'\"");
if (value!==properValue) {
  console.log(value, properValue);
  throw("Incorrect: "+value+" !== "+properValue);
}
pending…
RegExp (multiple)
value = regexpMultiple("foo<>'\"");
if (value!==properValue) {
  console.log(value, properValue);
  throw("Incorrect: "+value+" !== "+properValue);
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment