htmlEncode

JavaScript performance comparison

Revision 14 of this test case created by Yuval

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

      
<script>
Benchmark.prototype.setup = function() {
  var html = document.body.innerHTML;
  var map = {
    "&": "&amp;",
    "'": "&#39;",
    '"': "&quot;",
    "<": "&lt;",
    ">": "&gt;"
  };
  var tempJqElement = $(document.createElement("div"));
  var tempElement = document.createElement("div");
  
  function replace_with_switch(c) {
    switch (c) {
    case "&":
      return "&amp;";
    case "'":
      return "&#39;";
    case '"':
      return "&quot;";
    case "<":
      return "&lt;";
    case ">":
      return "&gt;";
    }
  }
  
  function replace_with_map(c) {
    return map[c];
  }
  
  function replace_charcode(c) {
    return '&#'+c.charCodeAt(0)+';';
  }
  
  var re_all = /[&"'\<\>]/g;
  var re_amp = /&/g;
  var re_quot = /"/g;
  var re_apos = /'/g;
  var re_lt = /</g;
  var re_gt = />/g;
  
  var re_arr = [
    [re_amp, '&amp;'],
    [re_quot, '&quot;'],
    [re_apos, '&#39;'],
    [re_lt, '&lt;'],
    [re_gt, '&gt;']
  ];

};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
multiple replace()
return (html).replace(re_amp, '&amp;').replace(re_quot, '&quot;').replace(re_apos, '&#39;').replace(re_lt, '&lt;').replace(re_gt, '&gt;');
pending…
single replace with map
return (html).replace(re_all, replace_with_map);
pending…
single replace with switch
return (html).replace(re_all, replace_with_switch);
pending…
createTextNode with precreated element
tempElement.innerHTML = '';
tempElement.appendChild(document.createTextNode(html));
return tempElement.innerHTML;
pending…
createTextNode
var el = document.createElement('div');
el.appendChild(document.createTextNode(html));
return el.innerHTML;
pending…
use jQuery with pre-created element
return tempJqElement.text(html).html();
pending…
using textContent/innerText with precreated element
tempElement.innerText = tempElement.textContent = html;
return tempElement.innerHTML;
pending…
new Option
return new Option(html).innerHTML;
pending…
multiple replace using array
var t, i, _html = html;
for(var t, i = 0; t = re_arr[i]; i++) {
  _html = _html.replace(t[0], t[1]);
}
return _html;
pending…
convert to charCode entities
html.replace(re_all, replace_charcode);
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.

0 Comments