Skip to content

Improve performance of exception raise #160473

Open

Description

@eendebakpt

Feature or enhancement

At the end of _PyErr_SetObject() the value is a normalized BaseException instance. The function still took a new reference to Py_TYPE(value) and fetched the value's traceback, only for _PyErr_Restore() to set that traceback back on the same object, store the value and drop the type again. Instead we can call _PyErr_SetRaisedException() directly.

Benchmarks

Default build, single thread:

Benchmark base patch
raise E / except E (heap type) 174 ns 171 ns: 1.02x faster
raise E('message') / except E 210 ns 205 ns: 1.02x faster
raise KeyError(1) / except KeyError (static type) 192 ns 176 ns: 1.09x faster
d[1] / except KeyError (raised from C) 177 ns 170 ns: 1.04x faster
f() / except E (raise through a frame) 290 ns 284 ns: 1.02x faster
Geometric mean (ref) 1.04x faster

The gain is within binary layout noise range, but in the right direction.

Free-threaded build, N threads each running try: raise E / except E: pass with E defined
by the main thread:

case 1 thr 2 thr 4 thr 8 thr
ctl: isinstance(b, A) 1.00 1.00 1.00 1.00
raise E / except E 1.03-1.04 1.12-1.15 1.34-1.44 1.60-1.70

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Activity

  1. added
    type-featureA feature request or enhancement
    performancePerformance or resource usage
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    on Oct 23, 2026
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

    interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions