html encode

JavaScript performance comparison

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("&", '&amp;').replace('"', '&quot;').replace("'", '&#39;').replace("<", '&lt;').replace(">", '&gt;')
    }
   
    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…
regex
doEncode(endcodeWithRegEx)
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