Hex to RGB (v6)

Revision 6 of this benchmark created 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;
  }
  
  var hexToRgb5 = function(hex) {
    var r = parseInt(hex.substring(0, 2), 16),
      g = parseInt(hex.substring(2, 4), 16),
      b = parseInt(hex.substring(4, 6), 16);
  
    return r + "," + g + "," + b;
  }
  
  var hexToRgb6 = function(hex) {
    var r = parseInt(hex[0] + hex[1], 16),
      g = parseInt(hex[2] + hex[3], 16),
      b = parseInt(hex[4] + hex[5], 16);
  
    return r + "," + g + "," + b;
  }

Test runner

Ready to run.

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

Revisions

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