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 & \" ' < >")
}
};
</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… |
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