I've created this function to convert RGB color to HSL color. It works perfect.
But I need to make it run faster, because it's used to replace colors on a canvas, and I need to reduce the time of replacement. Since the image contains 360k pixels (600x600px) anything can make it faster.
That's my current implementation:
/**
* Convert RGB Color to HSL Color
* @param {{R: integer, G: integer, B: integer}} rgb
* @returns {{H: number, S: number, L: number}}
*/
Colorize.prototype.rgbToHsl = function(rgb) {
var R = rgb.R/255;
var G = rgb.G/255;
var B = rgb.B/255;
var Cmax = Math.max(R,G,B);
var Cmin = Math.min(R,G,B);
var delta = Cmax - Cmin;
var L = (Cmax + Cmin) / 2;
var S = 0;
var H = 0;
if (delta !== 0) {
S = delta / (1 - Math.abs((2*L) - 1));
switch (Cmax) {
case R:
H = ((G - B) / delta) % 6;
break;
case G:
H = ((B - R) / delta) + 2;
break;
case B:
H = ((R - G) / delta) + 4;
break;
}
H *= 60;
}
// Convert negative angles from Hue
while (H < 0) {
H += 360;
}
return {
H: H,
S: S,
L: L
};
};
tl;dr
Math.max
andMath.min
(if-else
works better for bigger numbers as far as I can see)Benchmark
The benchmark is quite basic; I'm generating a random RGB color every time and use it for the test suit.
The same color for all implementations of a converter.
I'm currently using a fast computer, so your numbers may differ.
At this point it is hard to optimize further, because performance differs, depending on the data.
Optimisations
Define the object for the result value at the very beginning. Allocating memory for the objects upfront somehow improves the performance.
Not using
switch
will yield easy performance improvement.While loop is easily removable by:
I have also applied Closure Compiler to remove redundant operations inside of the code.
You should memoize the results!
Consider refactoring the function to use three arguments so it's possible to have a multi-dimensional hash-map for memozing cache. Alternatively you can try using WeakMap, but the performance of this solution is unknown.
See the article Faster JavaScript Memoization For Improved Application Performance
Results
Node.js
The best one is
rgbToHslOptimizedClosure
.Browser
Run the benchmark yourself
Note, that browser will freeze for a moment.