python / python/cpython

Use tagged ints for faster iteration

Open
#132,554 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core performance type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Iteration over tuples and short lists is quite inefficient as we need to create an iterator object, only to have to destroy it again moments later. Not only that, fetching values from iterators involves additional indirection compared to fetching them from sequences.

Instead we can push a pair of values to the stack. For common sequences, like tuple, list, strings, some ranges and a few others, we push the sequence and the integer index (initially 0) to the stack. For other iterables, we push the iterator and NULL.

GET_ITER will have the signature:
iterable -- iter, index_or_null
FOR_ITER now has the signature:
iter, index_or_null -- iter, index_or_null, next.

What makes this efficient is tagged integers. By using tagged integers, no objects need to be created.

Examples
GET_ITER

[ <tuple at ...> ] -> [ <tuple at ...>, 0 ]

[ <file at ...> ] -> [ <file iterator at ...>, NULL ]

FOR_ITER

[ <tuple at ...>, 0 ] -> [ <tuple at ...>, 1, item0 ]

[ <file iterator at ...>, NULL ] -> [ <file iterator at ...>, NULL, line ]

Linked PRs
  • gh-132555
  • gh-132592
  • gh-135063
  • gh-135137

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Begin with linked PRs gh-132555, gh-132592, gh-135063, and gh-135137 to determine the current implementation status, then trace the GET_ITER and FOR_ITER stack signatures described here. Done means common sequences use tagged integer indices without iterator objects while other iterables retain an iterator and NULL.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, performance
Issue type
Refactor
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.