Text width

JavaScript performance comparison

Revision 4 of this test case created by Brandon Bloom

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

      
<script>
Benchmark.prototype.setup = function() {
  var create = function(hide) {
    var span = document.createElement('span');
    if (hide) span.style.visibility = "hidden";
    span.style.whiteSpace = "nowrap";
    span.style.margin = span.style.padding = 0;
    document.body.appendChild(span);
    return span;
  };
  
  var shown = create(false);
  var hidden = create(true);
  
  $.fn.measureWidth = function() {
    shown.innerHTML = this.outerHTML;
    return shown.offsetWidth;
  }
  
  $.fn.measureWidthHidden = function() {
    hidden.innerHTML = this.outerHTML;
    return hidden.offsetWidth;
  }
  
  $.fn.canvasMeasureWidth = function() {
    if (!jQuery._cacheCanvas) {
      var canvas = document.createElement('canvas');
      var docFragment = document.createDocumentFragment();
      docFragment.appendChild(canvas);
      jQuery._cacheCanvas = canvas;
    }
    return jQuery._cacheCanvas.getContext("2d").measureText(text).width;;
  }
  
  var text = "YOU SHALL NOT PASS!";

};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Check width on not hidden
$("<p>" + text + "</p>").measureWidth();
pending…
The same with hidden
$("<p>" + text + "</p>").measureWidthHidden();
pending…
Cached canvas
$("<p>" + text + "</p>").canvasMeasureWidth();
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.

0 Comments