htmlEncode
JavaScript performance comparison
Info
Add a test using split and join, like the encode function in jQuery Templates.
Preparation code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
var html = document.body.innerHTML;
var map = {
"&": "&",
"'": "'",
'"': """,
"<": "<",
">": ">"
};
var tempJqElement = $(document.createElement("div"));
var tempElement = document.createElement("div");
function replace_with_switch(c) {
switch (c) {
case "&":
return "&";
case "'":
return "'";
case '"':
return """;
case "<":
return "<";
case ">":
return ">";
}
}
function replace_with_map(c) {
return map[c];
}
function replace_charcode(c) {
return '&#'+c.charCodeAt(0)+';';
}
var re_all = /[&"'\<\>]/g;
var re_amp = /&/g;
var re_quot = /"/g;
var re_apos = /'/g;
var re_lt = /</g;
var re_gt = />/g;
var re_arr = [
[re_amp, '&'],
[re_quot, '"'],
[re_apos, '''],
[re_lt, '<'],
[re_gt, '>']
];
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
multiple replace() |
|
pending… |
single replace with map |
|
pending… |
single replace with switch |
|
pending… |
createTextNode |
|
pending… |
use jQuery with pre-created element |
|
pending… |
using textContent/innerText with precreated element |
|
pending… |
new Option |
|
pending… |
createTextNode with precreated element |
|
pending… |
multiple replace using array |
|
pending… |
convert to charCode entities |
|
pending… |
Split and join |
|
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 yuval
- Revision 2: published
- Revision 3: published
- Revision 5: published
- Revision 6: published
- Revision 7: published
- Revision 8: published by Eamon Nerbonne
- Revision 9: published
- Revision 11: published
- Revision 14: published by Yuval
- Revision 15: published by Ian Obermiller
- Revision 16: published by ThinkingStiff
- Revision 17: published by ThinkingStiff
- Revision 18: published
- Revision 20: published by Prestaul
0 comments