html encode

JavaScript performance comparison

Revision 10 of this test case created by Dan Rzeppa

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function encodeWithIfs(str) {
    var result = ""
    for (var cc = 0; cc < str.length; cc++) {
      var c = str.charAt(cc)
      if (c == "&") result += '&amp;'
      else if (c == '"') result += '&quot;'
      else if (c == "'") result += '&#39;'
      else if (c == "<") result += '&lt;'
      else if (c == ">") result += '&gt;'
      else result += c
    }
    return result
  }
  
  function endcodeWithRegEx(str) {
    return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  }
  
  function endcodeWithRegEx2(str) {
    return str.replace(/[&<>"'`]/g, function(chr) {
      return '&#' + chr.charCodeAt(0) + ';'
    })
  }
  
  function doEncode(func) {
    var a = func("<div></div>")
    var b = func("This is a string with no replacements")
    var c = func("All replacement chars & \" ' < >")
  }
  
  var goog_string_amperRe_ = /&/g;
  var goog_string_ltRe_ = /</g;
  var goog_string_gtRe_ = />/g;
  var goog_string_quotRe_ = /\"/g;
  var goog_string_allRe_ = /[&<>\"]/;
  
  function goog_string_htmlEscape(str) {
    // quick test helps in the case when there are no chars to replace, in
    // worst case this makes barely a difference to the time taken
    if (!goog_string_allRe_.test(str)) return str;
  
    // str.indexOf is faster than regex.test in this case
    if (str.indexOf('&') != -1) {
      str = str.replace(goog_string_amperRe_, '&amp;');
    }
    if (str.indexOf('<') != -1) {
      str = str.replace(goog_string_ltRe_, '&lt;');
    }
    if (str.indexOf('>') != -1) {
      str = str.replace(goog_string_gtRe_, '&gt;');
    }
    if (str.indexOf('"') != -1) {
      str = str.replace(goog_string_quotRe_, '&quot;');
    }
    return str;
  }

};
</script>

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
ifs
doEncode(encodeWithIfs)
pending…
regex1
doEncode(endcodeWithRegEx)
pending…
regex2
doEncode(endcodeWithRegEx2)
pending…
goog_string_htmlEscape
doEncode(goog_string_htmlEscape)
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