rgbtohex

JavaScript performance comparison

Revision 5 of this test case created by Garrett

Preparation code

<script>
  var red = 0,
      green = 150,
      blue = 145.67;
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Raphael
var r = (~~red).toString(16)
var g = (~~green).toString(16)
var b = (~~blue).toString(16)
var hex = r + g + b;
pending…
2
var hex = '#' + (0x1000000 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
pending…
Garrett's
var toHexString = function (r, g, b) {
  return (toHexString = _toHexString)(r,g,b);
  function _toHexString(r, g, b) {
    return "#" + toHexByte(r) + toHexByte(g) + toHexByte(b);
  }
  function toHexByte(bite) {
    var hex = bite.toString(16);
    return (hex.length === 2 ? hex : "0" + hex);
  }
};
var hex = toHexString(red, green, blue);
pending…
atesgoral's
function toHexString(a,b,c){
  return"#"+((256+a<<8|b)<<8|c).toString(16).slice(1);
}
var hex = toHexString(red, green, blue);
pending…
Jed's
function toHexString(a,b,c){
  return"#"+((256+a<<8|b)<<8|c).toString(16).slice(1);
}
var hex = toHexString(red, green, blue);
pending…
Asen's
function toHexString(r,g,b) {
  return ("00000" + (r << 16 | g << 8 | b).toString(16)).slice(-6);
}
var hex = toHexString(red, green, blue);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

Mathias Bynens commented :

This benchmark also tests the time it takes to declare the function. Ideally, the function declarations should go in the preparation/setup code, so that you only really benchmark what you want to benchmark.

By the way, Atesgoral’s and Jed’s solutions are identical, so I removed one.

I’ve taken care of all this in my fork: http://jsperf.com/rgbtohex/6

Add a comment