Skip to content

perf: Remove sqrt in palette match #4213

Description

@Leuchak

sqrt is not needed when only the minimum distance is required.

diff --git i/rich/palette.py w/rich/palette.py
index f2958794..8c6ba963 100644
--- i/rich/palette.py
+++ w/rich/palette.py
@@ -1,4 +1,3 @@
-from math import sqrt
 from functools import lru_cache
 from typing import Sequence, Tuple, TYPE_CHECKING
 
@@ -52,17 +51,16 @@ class Palette:
             int: Index of closes matching color.
         """
         red1, green1, blue1 = color
-        _sqrt = sqrt
         get_color = self._colors.__getitem__
 
-        def get_color_distance(index: int) -> float:
+        def get_color_distance(index: int) -> int:
             """Get the distance to a color."""
             red2, green2, blue2 = get_color(index)
             red_mean = (red1 + red2) // 2
             red = red1 - red2
             green = green1 - green2
             blue = blue1 - blue2
-            return _sqrt(
+            return (
                 (((512 + red_mean) * red * red) >> 8)
                 + 4 * green * green
                 + (((767 - red_mean) * blue * blue) >> 8)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions