Skip to content

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

Description

@uwu-crj

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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