python / python/cpython

tuple unpacking is slower than tuple(list comprehension)

未關閉
#138,325 19 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core performance type-feature
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

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

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

首先重現 issue 中的四個基準表達式,並比較 tuple unpacking 與 tuple 建構。查看已連結的 PR gh-149960,了解已在進行的工作;當慣用的 generator 形式不再落後於最快的形式,且不破壞所述的 fallback 行為時,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
compilers, performance
Issue 類型
功能
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。