Text width (v3)

Revision 3 of this benchmark created on


Preparation HTML

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

Setup

$.fn.measureWidth = function() {
    var span = jQuery._cacheSpan;
    if (!span) {
      var span = document.createElement('span');
      span.style.whiteSpace = "nowrap";
      span.style.margin = span.style.padding = 0;
      jQuery._cacheSpan = span;
    }
    span.innerHTML = this.outerHTML;
    return span.offsetWidth;
  }
  
  $.fn.measureWidthHide = function() {
    var span = jQuery._cacheSpanHide;
    if (!span) {
      var span = document.createElement('span');
      span.style.whiteSpace = "nowrap";
      span.style.margin = span.style.padding = 0;
      span.style.visibility = "hidden";
      jQuery._cacheSpanHide = span;
    }
    span.innerHTML = this.outerHTML;
    return span.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!";

Test runner

Ready to run.

Testing in
TestOps/sec
Check width on not hidden
$("<p>" + text + "</p>").measureWidth();
ready
The same with hidden
$("<p>" + text + "</p>").measureWidthHide();
ready
Cached canvas
$("<p>" + text + "</p>").canvasMeasureWidth();
ready

Revisions

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