Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Usefor instead ofnext incontextlib.contextmanager#141275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
brandtbucher wants to merge1 commit intopython:main
base:main
Choose a base branch
Loading
frombrandtbucher:contextlib

Conversation

@brandtbucher
Copy link
Member

This is a fun little optimization. According to some local microbenchmarks (basically entering and exiting context managers a million times), turning thesenext calls intofor loops saves about 25% of the overhead this class introduces (~5% due to__enter__ and ~20% due to__exit__). This is because:

  • The wrapped iterator is usually a generator. We specializefor loops for generators, so instead of calling through the C code fornext and re-entering the interpreter, we can "inline" the frame push instead. (This is also more JIT-friendly.)
  • We don't care about the actualStopIteration exceptions here, just whether or not they were raised. Raising exceptions is expensive, and the interpreter has an optimization to avoid actually raisingStopIteration in normalfor loops. (This is especially helpful in__exit__, where we advance the generator, expect aStopIteration to be raised, and then just throw it away!)

This change isn't worth it for theasync variant of this function, since neither of the above optimizations apply toasync for loops.

@brandtbucherbrandtbucher self-assigned thisNov 9, 2025
@brandtbucherbrandtbucher added performancePerformance or resource usage skip issue skip news stdlibStandard Library Python modules in the Lib/ directory labelsNov 9, 2025
@picnixz
Copy link
Member

For tracking purposes, could you create an issue for that please? I also think it's worth a NEWS entry for people who are interested in this kind of optimization and understanding it.

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

Reviewers

No reviews

Assignees

@brandtbucherbrandtbucher

Labels

awaiting core reviewperformancePerformance or resource usageskip newsstdlibStandard Library Python modules in the Lib/ directory

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@brandtbucher@picnixz

[8]ページ先頭

©2009-2025 Movatter.jp