dtao / nearest-color

Find the nearest color

Home Page:danieltao.com/nearest-color

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

superfluous and costly sqrt

redchair123 opened this issue · comments

https://github.com/dtao/nearest-color/blob/master/nearestColor.js#L70-L83 a square root is performed in every iteration. Since you are comparing square roots to other square roots, it would be faster to compare the square distances and take the square root at the end:

    for (var i = 0; i < colors.length; ++i) {
      rgb = colors[i].rgb;

      /* distance is the square of the actual distance */
      distance = (
        Math.pow(needle.r - rgb.r, 2) +
        Math.pow(needle.g - rgb.g, 2) +
        Math.pow(needle.b - rgb.b, 2)
      );

      /* comparison is still consistent: assuming a>0 and b>0, then a > b if and only if sqrt(a) > sqrt(b) */
      if (distance < minDistance) {
        minDistance = distance;
        value = colors[i];
      }
    }

    /* take the sqrt at the end */
    minDistance = Math.sqrt(minDistance);

Good point! This should be easy enough to fix :)