html encode
JavaScript performance comparison
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 += '&'
else if (c == '"') result += '"'
else if (c == "'") result += '''
else if (c == "<") result += '<'
else if (c == ">") result += '>'
else result += c
}
return result
}
function endcodeWithRegEx(str) {
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>')
}
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_, '&');
}
if (str.indexOf('<') != -1) {
str = str.replace(goog_string_ltRe_, '<');
}
if (str.indexOf('>') != -1) {
str = str.replace(goog_string_gtRe_, '>');
}
if (str.indexOf('"') != -1) {
str = str.replace(goog_string_quotRe_, '"');
}
return str;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
ifs |
|
pending… |
regex1 |
|
pending… |
regex2 |
|
pending… |
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. Here’s a list of current revisions for this page:
- Revision 1: published by Dan Rzeppa
- Revision 2: published by Dan Rzeppa
- Revision 3: published by WebReflection
- Revision 4: published by Johan Sundström
- Revision 5: published
- Revision 8: published by Eamon Nerbonne
- Revision 9: published by Eamon Nerbonne
- Revision 10: published by Dan Rzeppa
- Revision 11: published by Dan Rzeppa
0 comments