htmlEncodeRegEx

JavaScript performance comparison

Revision 3 of this test case created

Preparation code

<script src="//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 tempElement = $(document.createElement("div"));
   
    var arr = [
      [/&/g, '&amp;'],
      [/'/g, '&#39;'],
      [/"/g, '
&quot;'],
      [/</g, '
&lt;'],
      [/>/g, '
&gt;']
    ];
    var better_map_fn = function(c) {
      return map[c];
    };
    var el_10 = document.createElement('
div');
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
multiple replace()
return html.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
pending…
single replace with map
return html.replace(/[&"'\<\>]/g, function(c) {
  return map[c];
});
pending…
single replace with switch
return html.replace(/[&"'\<\>]/g, function(c) {
  switch (c) {
  case "&":
    return "&amp;";
  case "'":
    return "&#39;";
  case '"':
    return "&quot;";
  case "<":
    return "&lt;";
  case ">":
    return "&gt;";
  }

});
pending…
use jQuery
return $('<div/>').text(html).html();
pending…
use jQuery with pre-created element
return tempElement.text(html).html();
pending…
string replace with array map
var t, i, _html = html;
for(var t, i = 0; t = arr[i]; i++) {
  _html = _html.replace(t[0], t[1]);
}
return _html;
pending…
ternary replace
return html.replace(/[&"'\<\>]/g,(a == "<") ? a="&lt;" : ((a == ">") ? a="&gt;" : ((a == "\"") ? a="&quot;" : (a == "\'") ? a='&#39;' : (a == "\&") ? a="&amp;" : a=a)));
pending…
vanilla element method
var el = document.createElement('div');
el.appendChild(document.createTextNode(html));
return el.innerHTML;
pending…
vanilla element method, with precreated element
el_10.innerHTML = '';
el_10.appendChild(document.createTextNode(html));
return el_10.innerHTML;
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