html-escaping

Benchmark created on


Setup

var escapeHTML1 = (function () {
        var controlChars = /["'<>&]/g;
    
        var encodedChars = {
            '&': '&amp;',
            '"': '&quot;',
            '\'': '&#39;',
            '<': '&lt;',
            '>': '&gt;'
        };
        function encodeChar(char) {
            return encodedChars[char];
        }
    
        return function (rawTxt) {
            return rawTxt.replace(controlChars, encodeChar);
        };
    })();
    
    var escapeHTML2 = (function () {
        var el = document.createElement('span');
        el.style.display = 'none';
    
        return function (rawTxt) {
            el.appendChild(document.createTextNode(rawTxt));
            return el.innerHTML;
        };
    })();
    
    var testStrings = [
        '<b>hello world, 1 & 2!</b>',
        'this string has absolutely no html in it and does not need anything done to it.'
    ];

Test runner

Ready to run.

Testing in
TestOps/sec
string replace
for (var i = 0, len = testStrings.length; i < len; i++) {
    escapeHTML1(testStrings[i]);
}
ready
dom hijack
for (var i = 0, len = testStrings.length; i < len; i++) {
    escapeHTML2(testStrings[i]);
}
ready

Revisions

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