13 October 2012

A fast way to get a Javascript hex colour conversion

Looking for a fast JavaScript way to get a conversion from integer rgb numbers these are my results for two methods:


function dotest() {
   var limtest=1000000;
   var ini_1= +new Date;
   for(var i=0;i<limtest;i++){
      var r = i % 255;
      var g = (limtest - i) % 255;
      var b = (r+g) % 255;
      var color = "#" +
          ("000000" + ((r << 16) | (g << 8) | b).toString(16)).slice(-6);

   }
   var fim_1= +new Date;
   var test1time = fim_1 - ini_1;
   var ini_2= +new Date;
   for(var i=0;i<limtest;i++){
      var r = i % 255;
      var g = (limtest - i) % 255;
      var b = (r+g) % 255;
      var color = "#" +
          ("0" + parseInt(r, 10).toString(16)).slice(-2) +
          ("0" + parseInt(g, 10).toString(16)).slice(-2) +
          ("0" + parseInt(b, 10).toString(16)).slice(-2);

   }
   var fim_2= +new Date;
   alert("test 1: " + test1time + " ms / test 2: " +
      (fim_2 - ini_2) + " ms");
}
window.onload = setTimeout(dotest,1000);




My results were:

opera 12.02 build1578:
test1: 553
test2: 1190
chrome 22.0.1229.94m:
test1: 739
test2: 1670
firefox 15.0.1:
test1: 1024
test2: 2430
IE 9.0.8112.16421:
test1: 1139
test2: 2754
IE 9.0.8112.16421 64bit:
test1: 1348
test2: 3461


Less expensive function calls on the first test (string concatenation +, parseInt, etc) make it faster.

Update: made a jsperf Javascript test with 4 methods (including these). The result set suggests that the fastest method is:

"#" + (0x1000000 | (r<<16) | (g<<8) | b).toString(16).slice(1);
(in operations used is similar to the first in this post but gains in replacing one string concatenation (+) with a bitwise OR)

Update: If you are looking for a way to convert back and forth from "#012ABC" or rgb(1,2,3) string into numbers you may wish to inspect the parts that interest you in another post.

No comments:

Post a Comment