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

オープン
#157,840 コメント 0 件 リアクション 0 件 担当者 1 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
45/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
技術スタック
python
領域
performance

調査の方向性

まず、issue にある 2 つの Python 3.14 の timeit コマンドを再現し、属性が存在しない場合と値が設定されていないスロットの場合を比較します。その違いの原因となっているスロット検索と hasattr の経路を追跡します。値が設定されていないスロットの場合が測定可能な形で改善され、hasattr の False の結果や既存の動作を変更していなければ完了です。

索引モデルが issue の本文から書いたものです。

説明

interpreter-core performance type-feature

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

Linked PRs
  • gh-157866
主要言語
Python
スター
77.2k
フォーク
36k
平均マージ
1日 9時間
マージ済み PR(30日)
558

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

python/cpython のほかの issue

python/cpython の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。