RGB to hex

JavaScript performance comparison

Revision 6 of this test case created by Mathias Bynens

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var red = 0,
        green = 150,
        blue = 145.67;
   
    // Raphaël.js
    function raphael(red, green, blue) {
      var r = (~~red).toString(16),
          g = (~~green).toString(16),
          b = (~~blue).toString(16);
      return r + g + b;
    }
   
    function rgbtohex2(red, green, blue) {
      return '#' + (0x1000000 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
    }
   
    // Garrett’s
    function garrett(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);
      }
    }
   
    // atesgoral’s
    function atesgoral(a,b,c) {
      return"#" + ((256 + a << 8 | b) << 8 | c).toString(16).slice(1);
    }
   
    // Asen’s
    function asen(r, g, b) {
      return ("00000" + (r << 16 | g << 8 | b).toString(16)).slice(-6);
    }
};
</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
raphael(red, green, blue);
pending…
2
rgbtohex2(red, green, blue);
pending…
Garrett’s
toHexString(red, green, blue);
pending…
atesgoral’s
atesgoral(red, green, blue);
pending…
Asen’s
asen(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:

0 comments

Add a comment