joevallender
joevallender

Reputation: 4293

optimise this script

Can anyone suggest a way to shave any time off this script?

var countObject = new Object();
var length = data.length;
for(var i = 0; i < length; i += 4) {
  var key = data[i] + ',' + data[i+1] + ',' + data[i+2];
  if(typeof(countObject[key]) == 'number') {
    countObject[key]++
  } else {
    countObject[key] = 0
  }  
}

It is to build up a count of occurrences of RGB values found in data retrieved from a canvas. Presumably the data from context.getImageData() is already an optimised array type...?

EDIT: I do not require the RGB value in the format "255,255,255" necessarily, it's just all I could come up with for use as the array key. A different approach is also welcome :-D

Upvotes: 1

Views: 76

Answers (2)

Hamish
Hamish

Reputation: 23316

I don't know if this is going to make any significant difference (you'd have to have a lot of values to see any appreciable performance difference), but you could:

  • Create keys using fast bit shifting operations instead of slow string concatenation
  • Cut out a few steps in the assignment:

So:

for(var i = 0, l = length; i < l; i += 4) {
   var key = (data[i] << 16) + (data[i+1] << 8) + data[i];
   countObject[key] = (countObject[key] || 0) + 1;
}

EDIT: Since you mentioned getting the RGB value back from the key, here is how it's done:

/** 
 * From a color key (integer)  return an object 
 * with keys 'r', 'g' and 'b'
 */
var colorFromKey = function(key) {
   return {
      'r': (key >> 16) & 0xFF,
      'g': (key >> 8) & 0xFF,
      'b': key & 0xFF
   };
}

Upvotes: 2

Bergi
Bergi

Reputation: 664599

Can anyone suggest a way to shave any time off this script?

No, seems fine, but I have some other suggestions:

var countObject = new Object(); // use {} instead, that's more common
var length = data.length; // why that? You are already using var l=...
for(var i = 0, l = length; i < l; i += 4) {
  var key = data[i] + ',' + data[i+1] + ',' + data[i+2];
  if(typeof(countObject[key]) == 'number') { // remove the brackets. typeof is no function
    countObject[key]++ // ; missing
  } else {
    countObject[key] = 0 // are you sure this should not start with 1?
  }  
}

If you have a colorful image, it may be faster to do the initialisation of the countObject before (setting every possible key to 0). Then you save the if-condition for every iteration.

Upvotes: 1

Related Questions