Skip to content

tuple unpacking is slower than tuple(list comprehension) #138325

@user202729

Description

@user202729

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

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