python / python/cpython

hasattr() performance is bad on a slot that has no value

未關閉
#157,840 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

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

描述

Bug report

Bug description:

Compare these two timeit invocations:

$ python3.14 -m timeit -s 'class Test: pass' -s 't = Test()' 'hasattr(t,"x")'
10000000 loops, best of 5: 33.5 nsec per loop
$ python3.14 -m timeit -s 'class Test: __slots__ = ("x",)' -s 't = Test()' 'hasattr(t,"x")'
1000000 loops, best of 5: 241 nsec per loop

Observe that in the case where Test.x is a slot, hasattr takes 241 ns to return False while it only takes 33.5 ns when there is no Test.x slot.

Peter Bierma advised me to file an issue when I asked about this in Discourse.

CPython versions tested on:

3.14, 3.13, 3.12

Operating systems tested on:

Linux

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

首先重現 issue 中的兩個 Python 3.14 timeit 命令,並比較缺少屬性的情況與未賦值 slot 的情況。追蹤造成差異的 slot 查找與 hasattr 路徑。完成的標準是未賦值 slot 的情況得到可測量的改善,同時不改變 hasattr 的 False 結果或現有行為。

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

評估

技術堆疊
python
領域
performance
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
活躍
描述清晰度
基本清楚
新手友好度
45/100

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

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