decoding html entities

JavaScript performance comparison

Test case created by Ben Loveridge

Info

Compares blindly using the DOM to convert HTML entities to strings, vs checking first for presence of & and ;

Since I will be using this on strings of varying length (some quite long) I am using an exaggerated example to test worst-case scenarios.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var base_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eu ante orci. Morbi a quam pulvinar mi facilisis commodo imperdiet eu justo. Suspendisse metus dui, luctus vel convallis quis, interdum ut diam. Cras neque erat, commodo eu pretium in, fermentum at erat. Suspendisse lorem metus, pellentesque id sodales ut, pellentesque non nulla. Nunc placerat sem eget augue congue placerat ullamcorper magna dapibus. Quisque nec leo non mauris suscipit sagittis. Curabitur at orci tellus. &.";
   
    var string_with_entities = base_string + " &copy; 2013 Awesome Sauce Productions &trade;"
   
    var span, converted;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
blind dom usage - no entities
span = document.createElement("span");
span.innerHTML = base_string;
converted = span.firstChild.nodeValue;
pending…
blind dom usage - entities
span = document.createElement("span");
span.innerHTML = string_with_entities;
converted = span.firstChild.nodeValue;
pending…
if first - no entities
if (base_string.indexOf("&") > -1) {
  span = document.createElement("span");
  span.innerHTML = base_string;
  converted = span.firstChild.nodeValue;
}
else {
  converted = base_string;
}
pending…
if first - entities
if (string_with_entities.indexOf("&") > -1) {
  span = document.createElement("span");
  span.innerHTML = string_with_entities;
  converted = span.firstChild.nodeValue;
}
else {
  converted = string_with_entities;
}
pending…
double if first - no entities
if (base_string.indexOf("&") > -1 && base_string.indexOf(";") > -1) {
  span = document.createElement("span");
  span.innerHTML = base_string;
  converted = span.firstChild.nodeValue;
}
else {
  converted = base_string;
}
pending…
double if first - entities
if (string_with_entities.indexOf("&") > -1 && string_with_entities.indexOf(";") > -1) {
  span = document.createElement("span");
  span.innerHTML = string_with_entities;
  converted = span.firstChild.nodeValue;
}
else {
  converted = string_with_entities;
}
pending…

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

Compare results of other browsers

0 comments

Add a comment