Skip to content

PERF: Bezier root finding speedup#31005

Open
scottshambaugh wants to merge 3 commits intomatplotlib:mainfrom
scottshambaugh:bezier_speedups
Open

PERF: Bezier root finding speedup#31005
scottshambaugh wants to merge 3 commits intomatplotlib:mainfrom
scottshambaugh:bezier_speedups

Conversation

@scottshambaugh
Copy link
Contributor

@scottshambaugh scottshambaugh commented Jan 20, 2026

PR summary

This speeds up Path.get_extents which calls these bezier operations.

Instead of np.roots which does expensive eigenvalue decomposition, we can take advantage of the fact that we are only looking for roots on the limited [0, 1] interval and just do bisection for degree >= 3. Or we can calculate exactly for degree == 2. These both end up being much faster.

This code section is circled below in the profiler runs.

Before:
image

After:
image

Profiling test script:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

n = 1000
rng = np.random.default_rng(42)
x = rng.random(n)
y = rng.random(n)
for i in range(n):
    ax.scatter(x[i], y[i])

fig.canvas.draw()
plt.close(fig)

PR checklist

@timhoffm
Copy link
Member

timhoffm commented Feb 2, 2026

Can you please split the two changes? I would like to review and discuss them separately.

For the coefficient matrices, I'd like to have a built-in guarantee that the matrix and the formula yield the same result. This can be achieved in one of two ways:

  • use caching instead of hard-coding; i.e. calculate them the first time they occur.
  • or factor out the calculation into a separate private function and write a test that the hard-coded matices and calculated matrices for n<=4 match.

@scottshambaugh
Copy link
Contributor Author

scottshambaugh commented Feb 2, 2026

Sure thing @timhoffm, I split the coefficient calcs into #31059 and refactored that to cache the poly coefficient matrices rather than hardcoding them. The root-finding changes remain in this PR, and the description is updated with some screenshots of the profiling changes.

@scottshambaugh scottshambaugh changed the title PERF: Bezier speedups PERF: Bezier root finding speedup Feb 2, 2026
@timhoffm
Copy link
Member

timhoffm commented Feb 3, 2026

Please fix the stubtest

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants