html encode

JavaScript performance comparison

Revision 2 of this test case created by Dan Rzeppa

Info

Speed test escaping html characters with if statements and regular expressions.

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 & \" ' < >")
    }
};
</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
ifs
doEncode(encodeWithIfs)
pending…
regex1
doEncode(endcodeWithRegEx)
pending…
regex2
doEncode(endcodeWithRegEx2)
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