Hex to RGB

Benchmark created by mk on


Setup

var data = [];
  for(var i = 0; i < 10000; i++)
  {
      data.push(Math.floor(Math.random() * 16777215).toString(16));
  }
  
  var hexToRgb1 = function(hex) {
      var bigint = parseInt(hex, 16);
      var r = (bigint >> 16) & 255;
      var g = (bigint >> 8) & 255;
      var b = bigint & 255;
  
      return r + "," + g + "," + b;
  }
  
  var hexToRgb2 = function(hex) {
      var bigint = parseInt(hex, 16);
      var r = (bigint >> 16) & 255;
      var g = (bigint >> 8) & 255;
      var b = bigint & 255;
  
      return [r, g, b].join();
  }
  
  var hexToRgb3 = function(hex) {
      return [(bigint = parseInt(hex, 16)) >> 16 & 255, bigint >> 8 & 255, bigint & 255].join();
  }
  
  var hexToRgb4 = function(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})|([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i.exec(hex);
    return result ? {        
      r: parseInt(hex.length <= 4 ? result[4]+result[4] : result[1], 16),
      g: parseInt(hex.length <= 4 ? result[5]+result[5] : result[2], 16),
      b: parseInt(hex.length <= 4 ? result[6]+result[6] : result[3], 16),
      toString: function() {
        var arr = [];
        arr.push(this.r);
        arr.push(this.g);
        arr.push(this.b);
        return "rgb(" + arr.join(",") + ")";
      }
    } : null;
  }

Test runner

Ready to run.

Testing in
TestOps/sec
hexToRgb4
var test;
for(var i = 0; i < data.length; i++)
{
    test = hexToRgb4(data[i]);
}
ready
hexToRgb3
var test;
for(var i = 0; i < data.length; i++)
{
    test = hexToRgb3(data[i]);
}
ready
hexToRgb2
var test;
for(var i = 0; i < data.length; i++)
{
    test = hexToRgb2(data[i]);
}
ready
hexToRgb1
var test;
for(var i = 0; i < data.length; i++)
{
    test = hexToRgb1(data[i]);
}
ready

Revisions

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