Canvas vs Loop

Benchmark created on


Preparation HTML

<div id="trunc"></div>

Setup

const trunc = document.querySelector('#trunc')
const context = document.createElement('canvas').getContext('2d');

trunc.textContent = 'x'.repeat(1000);

Test runner

Ready to run.

Testing in
TestOps/sec
Canvas
const computed = getComputedStyle(trunc);
const fontFamily = computed.fontFamily;
const fontSize = computed.fontSize;
const fontWeight = computed.fontWeight;
const text = trunc.textContent || '';

context.font = `${fontWeight} ${fontSize} ${fontFamily}`;

for (i = 0; i < 1000; i++) {
  context.measureText(text).width
}
ready
Loop
let dot = '…';
let text = trunc.textContent || '';
let start = trunc.textContent.slice(0, Math.ceil(text.length / 2));
let end = trunc.textContent.slice(-Math.floor(text.length / 2));
  
trunc.setAttribute('data-text', text)
  
for (i = 0; i < 1000; i++) {
  start = start.slice(0, -1);
  end = end.slice(1);
  text = start + dot + end;
  check = trunc.clientWidth < trunc.scrollWidth
  trunc.setAttribute('data-text', text)
}
ready

Revisions

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