3 rgb ints to hexcolor string

JavaScript performance comparison

Test case created by FranciscoM

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var dataSource = "sameRndVals"; //same random numbers for all tests ('sameRndVals', 'RndVals' or 'preset')
  var case_ds_sameRndVals_nitems = 200;
  var case_ds_preset_data = [0,1,2,32,64,128,115,118,121];
  
  if(window.test_cEfE40pY_it === undefined){
    switch (dataSource) {
      case "sameRndVals": 
        var sit = window.test_cEfE40pY_it = 
          {data: [], current: -1};
        for(var i=0; i< case_ds_sameRndVals_nitems*3; i++)
          sit.data.push(Math.random()*256 | 0); // | 0 quick floor
        sit.rewind = function () { sit.current=0; }
        sit.next = function () {
          if(++sit.current === sit.data.length)
            sit.current=0;
          return(sit.data[sit.current]);
        }
        break;
      case "RndVals": 
        window.test_cEfE40pY_it = {
          rewind :  function () { },
          next: function () { return Math.random()*256 | 0;}
        };
        break;
      case "preset":
      default: 
        var sit = window.test_cEfE40pY_it = 
          {data: case_ds_preset_data, current: -1};
        sit.rewind = function () { sit.current=0; }
        sit.next = function () {
          if(++sit.current === sit.data.length)
            sit.current=0;
          return(sit.data[sit.current]);
        };
    }
  }
  var it = window.test_cEfE40pY_it;
  it.rewind();
  

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
m0
var r = it.next();
var g = it.next();
var b = it.next();

var color = "#" + 
            ("000000" + ((r << 16) | (g << 8) | b).toString(16)).slice(-6);
pending…
m1
var r = it.next();
var g = it.next();
var b = it.next();

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);
pending…
m2
var r = it.next();
var g = it.next();
var b = it.next();

var color = "#" + 
            (0x1000000 | (r<<16) | (g<<8) | b).toString(16).slice(1);
pending…
m3
var r = it.next();
var g = it.next();
var b = it.next();

var color = "#" + 
    (r.toString(16).length == 1 ? "0" + r.toString(16) : r.toString(16)) + 
    (g.toString(16).length == 1 ? "0" + g.toString(16) : g.toString(16)) + 
    (b.toString(16).length == 1 ? "0" + b.toString(16) : b.toString(16));
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.

0 Comments