text width measurement

Benchmark created on


Setup

window.cachedCanvas = null;
window.cachedContext = null;

function measureTextWidthInPixelsOriginal(size, text) {
  if (typeof document === 'undefined') {
    return 0;
  }

  if (!cachedCanvas) {
    cachedCanvas = document.createElement('canvas');
    try {
      cachedContext = cachedCanvas.getContext('2d');
    } catch (e) {
      cachedContext = null;
    }
  }

  if (!cachedContext) {
    return 0;
  }

  cachedContext.font = `${size}px system-ui`;
  const w = cachedContext.measureText(text).width;
  return w;
}

function measureTextWidthInPixelsDesync(size, text) {
  if (typeof document === 'undefined') {
    return 0;
  }

  if (!cachedCanvas) {
    cachedCanvas = document.createElement('canvas', {
      alpha: false,
      desynchronized: true,
      willReadFrequently: true,
    });
    try {
      cachedContext = cachedCanvas.getContext('2d');
    } catch (e) {
      cachedContext = null;
    }
  }

  if (!cachedContext) {
    return 0;
  }

  cachedContext.font = `${size}px system-ui`;
  const w = cachedContext.measureText(text).width;
  return w;
}



function measureTextWidthInPixelsOffscreen(size, text) {
  if (typeof document === 'undefined') {
    return 0;
  }

  if (!cachedCanvas) {
    cachedCanvas = new OffscreenCanvas(1, 1);
    try {
      cachedContext = cachedCanvas.getContext('2d');
    } catch (e) {
      cachedContext = null;
    }
  }

  if (!cachedContext) {
    return 0;
  }

  cachedContext.font = `${size}px system-ui`;
  const w = cachedContext.measureText(text).width;
  return w;
}

Test runner

Ready to run.

Testing in
TestOps/sec
original
measureTextWidthInPixelsOriginal(12, 'some few words')
ready
desync
measureTextWidthInPixelsDesync(12, 'some few words')
ready
offscreen
measureTextWidthInPixelsOffscreen(12, 'some few words')
ready

Revisions

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