diff --git a/src/bokeh/palettes.py b/src/bokeh/palettes.py index 2d899faaeb5..c6153daa1e9 100644 --- a/src/bokeh/palettes.py +++ b/src/bokeh/palettes.py @@ -412,13 +412,6 @@ import logging # isort:skip log = logging.getLogger(__name__) - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - -# Standard library imports -import math from copy import deepcopy from typing import TYPE_CHECKING, TypeAlias @@ -1526,7 +1519,14 @@ def linear_palette(palette: Palette, n: int) -> Palette: """ if n > len(palette): raise ValueError(f"Requested {n} colors, function can only return colors up to the base palette's length ({len(palette)})") - return tuple( palette[math.floor(i)] for i in np.linspace(0, len(palette)-1, num=n) ) + # OPTIMIZATION: Precompute indices via numpy and use direct integer index lookup, + # avoiding costly math.floor and generator overhead. + indices = np.linspace(0, len(palette)-1, num=n) + # Use astype and list comprehension instead of generator expression and math.floor + idx = indices.astype(int) + # In case n == len(palette), idx will be [0, 1, ..., len(palette)-1] + # Performance gain from skipping math.floor in tight loop + return tuple(palette[i] for i in idx) def diverging_palette(palette1: Palette, palette2: Palette, n: int, midpoint: float = 0.5) -> Palette: """ Generate a new palette by combining exactly two input palettes.