8000 Micro-optimization of to_rgba_array. · matplotlib/matplotlib@78b6780 · GitHub
[go: up one dir, main page]

Skip to content

Commit 78b6780

Browse files
committed
Micro-optimization of to_rgba_array.
Avoid having to compute a repr of the entire array whenever calling to_rgba_array with an array input (that repr would be generated when the call to to_rgba fails and needs to generate an error message; instead, first check whether the input is already an array). See comments for detail. Slightly improves the performance of wire3d_animation on mpl_cairo.
1 parent bcc2f12 commit 78b6780

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

lib/matplotlib/colors.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -212,13 +212,6 @@ def to_rgba_array(c, alpha=None):
212212
If `alpha` is not `None`, it forces the alpha value. If `c` is "none"
213213
(case-insensitive) or an empty list, an empty array is returned.
214214
"""
215-
# Single value?
216-
if isinstance(c, six.string_types) and c.lower() == "none":
217-
return np.zeros((0, 4), float)
218-
try:
219-
return np.array([to_rgba(c, alpha)], float)
220-
except (ValueError, TypeError):
221-
pass
222215
# Special-case inputs that are already arrays, for performance. (If the
223216
# array has the wrong kind or shape, raise the error during one-at-a-time
224217
# conversion.)
@@ -234,6 +227,16 @@ def to_rgba_array(c, alpha=None):
234227
if np.any((result < 0) | (result > 1)):
235228
raise ValueError("RGBA values should be within 0-1 range")
236229
return result
230+
# Handle single values.
231+
# Note that this occurs *after* handling inputs that are already arrays, as
232+
# `to_rgba(c, alpha)` (below) is expensive for such inputs, due to the need
233+
# to format th 6C01 e array in the ValueError message(!).
234+
if isinstance(c, six.string_types) and c.lower() == "none":
235+
return np.zeros((0, 4), float)
236+
try:
237+
return np.array([to_rgba(c, alpha)], float)
238+
except (ValueError, TypeError):
239+
pass
237240
# Convert one at a time.
238241
result = np.empty((len(c), 4), float)
239242
for i, cc in enumerate(c):

0 commit comments

Comments
 (0)
0