Hex to RGB 2 (v12)

Revision 12 of this benchmark created on


Setup

function hextoRgb(hex) {
  if (/^#/i.test(hex)) {
    hex = hex.replace('#', '');
  }
  
  if (hex.length === 3) {
    const rHex = hex.substring(0,1);
    const gHex = hex.substring(1, 2);
    const bHex = hex.substring(2, 3);
    
    hex = `${rHex}${rHex}${gHex}${gHex}${bHex}${bHex}`;
  }
  
  const rDec = parseInt(hex.substring(0, 2), 16);
  const gDec = parseInt(hex.substring(2, 4), 16);
  const bDec = parseInt(hex.substring(4, 6), 16);
  
  return `rgb(${rDec},${gDec},${bDec})`;
}


function hextoRgb2(hex) {
  let r = 0x0;
  let b = 0x0;
  let g = 0x0;
  
  if (hex[0] === '#') {
    hex = hex.slice(1);
  }
  
  let num = parseInt(hex, 16);
  if (num <= 0xFFF) {
    b = num & 0xF;
    b |= b << 4;
    num >>= 4;
    g = num & 0xF;
    g |= g << 4;
    num >>= 4;
    r = num;
    r |= r << 4;
  } else {
    b = num & 0xFF;
    num >>= 8;
    g = num & 0xFF;
    num >>= 8;
    r = num;
  }
  return `rgb(${r},${g},${b})`;
}


const hextoRgb3 = hex => {
  let r = 0x0
  let b = 0x0
  let g = 0x0
  
  hex.startsWith('#') && (hex = hex.slice(1))
  let num = parseInt(hex, 16)
  
  if (num <= 0xFFF) {
    b = num & 0xF
    b |= b << 4
    num >>= 4
    g = num & 0xF
    g |= g << 4
    num >>= 4
    r = num
    r |= r << 4
  } else {
    b = num & 0xFF
    num >>= 8
    g = num & 0xFF
    num >>= 8
    r = num
  }
  return `rgb(${r},${g},${b})`
}

Test runner

Ready to run.

Testing in
TestOps/sec
Not optimized
hextoRgb("#123");
hextoRgb("#123123");
ready
Optimized
hextoRgb2("#123");
hextoRgb2("#123123");
ready
Optimized 2
hextoRgb3('#123')
hextoRgb3('#123123')
ready

Revisions

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