python / python/cpython

tuple unpacking is slower than tuple(list comprehension)

Open
#138,325 19 comments 1 reaction 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

Feature or enhancement

Proposal:
In []: %timeit (*(x**2 for x in range(1000)),)  # (A)
47.2 μs ± 1.18 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In []: %timeit tuple(x**2 for x in range(1000))  # most idiomatic
45.4 μs ± 5.57 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In []: %timeit (*[x**2 for x in range(1000)],)  # (B)
36.5 μs ± 77.8 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In []: %timeit tuple([x**2 for x in range(1000)])  # fastest
33.8 μs ± 710 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

Currently (A) and (B) are slower than the last one, even though it doesn't need to be so. There doesn't seem to be any bottleneck such as global namespace lookup.

Also, we want people to write the most idiomatic code, so it would be preferable to make the most idiomatic version to be as fast as the fastest version. Possibly with something like

if tuple is builtins.tuple:
    MAGIC
else:
    code as usual...
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
  • gh-149960

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

Start by reproducing the four benchmark expressions in the issue and compare tuple unpacking with tuple construction. Review linked PR gh-149960 for the work already under way; done means the idiomatic generator form no longer trails the fastest form without breaking the stated fallback behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, performance
Issue type
Feature
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.