htmlEncodeRegEx

JavaScript performance comparison

Revision 49 of this test case created by

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;",
    "\r\n": "<br/>",
    "\r": "<br/>",
    "\n": "<br/>"
  };
  var tempElement = $(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 CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
multiple replace()
return html.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(\r\n)/g, '<br/>').replace(/\r/g, '<br/>').replace(/\n/g, '<br/>');
pending…
single replace with map
return html.replace(/\r\n|[&"'\<\>\r\n]/g, function(c) {
  return map[c];
});
pending…
single replace with switch
return html.replace(/\r\n|[&"'\<\>\r\n]/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…

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