Compare String#replace with/without function

Benchmark created by Michael Jackson on


Setup

function escapeHTML1(s) {
      s = String(s === null ? "" : s);
      return s.replace(/&(?!\w+;)|["'<>\\]/g, function (s) {
        switch(s) {
        case "&": return "&amp;";
        case '"': return '&quot;';
        case "'": return '&#39;';
        case "<": return "&lt;";
        case ">": return "&gt;";
        default: return s;
        }
      });
    }
    
    function escapeHTML2(string) {
      if (string == null) return "";
      return String(string)
        .replace(/&(?!\w+;)/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
    }
    
    var escapeMap = {
      "&": "&amp;",
      '"': '&quot;',
      "'": '&#39;',
      "<": "&lt;",
      ">": "&gt;"
    };
    
    function escapeHTML3(s) {
      s = String(s === null ? "" : s);
      return s.replace(/&(?!\w+;)|["'<>\\]/g, function (s) {
        return escapeMap[s] || s;
      });
    }

Test runner

Ready to run.

Testing in
TestOps/sec
with function
escapeHTML1('<a href="#">A & B</a>');
 
ready
without function
escapeHTML2('<a href="#">A & B</a>');
 
ready
with function and map
escapeHTML3('<a href="#">A & B</a>');
 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Michael Jackson on