html escaping via dom
JavaScript performance comparison
Preparation code
<script>
Benchmark.prototype.setup = function() {
function coerceToString(val) {
return String((val === null || val === undefined) ? '' : val);
}
var rAmp = /&/g,
rLt = /</g,
rGt = />/g,
rApos = /\'/g,
rQuot = /\"/g,
hChars = /[&<>\"\']/;
var dom_escape = (function() {
var el = document.createElement('b');
if (el.textContent) {return (function(str) {
return hChars.test(str) ? (el.textContent = coerceToString(str), el.innerHTML) : str;
})} else {return (function(str) {
return hChars.test(str) ? (el.innerText = coerceToString(str), el.innerHTML) : str;
})}
})();
var hogan_escape = (function() {
return (function(str) {
str = coerceToString(str);
return hChars.test(str) ? str.replace(rAmp, '&').replace(rLt, '<').replace(rGt, '>').replace(rApos, ''').replace(rQuot, '"') : str;
});
})();
var split_escape = function(str) {
var input = coerceToString(str).split(/([&<>\"\'])/g);
var inputLengthM1 = input.length-1;
var output = [];
for (var i = 0; i < inputLengthM1; i += 2) {
var c = input[i+1];
output.push(input[i]);
output.push(
c == "'" ? ''' :
c == '"' ? '"' :
c == '&' ? '&' :
c == '<' ? '<' : '>');
}
output.push(input[inputLengthM1]);
return output.join('');
}
var split_concat_escape = function(str) {
var input = coerceToString(str).split(/([&<>\"\'])/g);
var inputLengthM1 = input.length-1;
var output = input[inputLengthM1];
for (var i = 0; i < inputLengthM1; i += 2) {
var c = input[i+1];
output = input[i] +
(
c == "'" ? ''' :
c == '"' ? '"' :
c == '&' ? '&' :
c == '<' ? '<' : '>') + output;
}
return output;
}
var roseta = {
"'" : ''',
'"' : '"',
'&' : '&',
'<' : '<' ,
'>' : '>'};
var split_concat_hash_escape = function(str) {
var input = coerceToString(str).split(/([&<>\"\'])/g);
var inputLengthM1 = input.length-1;
var output = input[inputLengthM1];
for (var i = 0; i < inputLengthM1; i += 2)
output = input[i] + roseta[input[i+1]] + output;
return output;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
dom |
|
pending… |
hogan |
|
pending… |
split join |
|
pending… |
split concat |
|
pending… |
split concat hash |
|
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 kmichel
- Revision 2: published by kmichel
0 comments