Text width (v5)

Revision 5 of this benchmark created on


Preparation HTML

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

Setup

window.computeWidthDOM = function(text, font) {
    var f = font || '12px arial';
    var o = computeWidthDOM.o = computeWidthDOM.o || $('<span></span>')
              .css({'visibility': 'hidden', 'font': f});
      o.text(text);    
      o.appendTo($('body')),
      w = o.innerWidth();
      o.remove();
      return w;
  }
  
  window.computeWidthCanvas =  function(text, font) {
      // re-use canvas object for better performance
      var canvas = computeWidthCanvas.canvas || (computeWidthCanvas.canvas = document.createElement("canvas"));
      var context = canvas.getContext("2d");
      context.font = font;
      var metrics = context.measureText(text);
      return metrics.width;
  };
  
  window.textFont = "12pt Arial";
  window.text = "YOU SHALL NOT PASS!";

Test runner

Ready to run.

Testing in
TestOps/sec
DOM-based method
computeWidthDOM(text, textFont)
ready
Canvas-based method
computeWidthCanvas(text, textFont);
ready

Revisions

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