Skip to content

Performance of PyObject_HasAttrString #104078

Closed

Description

@itamaro

Feature or enhancement

PyObject_HasAttrString is implemented in terms of PyObject_GetAttrString / PyErr_Clear.
for non-existing attributes, there's significant overhead from creating an error only to clear it later.
this can be optimized by implementing it in terms of PyObject_HasAttr.

microbenchmark

python -m pyperf timeit -s '
import _testcapi
hasattr_string = _testcapi.hasattr_string

class A:
  def __init__(self):
    self.attr = 1

a = A()' 'hasattr_string(a, "noattr")'
.....................
Mean +- std dev: 487 ns +- 7 ns

Linked PRs

Activity

  1. added
    type-feature
    on May 2, 2023
  2. added
    performance
    interpreter-core
    on May 2, 2023
  3. added a commit that references this issue on May 2, 2023
  4. ericvsmith commented on May 2, 2023

    @ericvsmith
    Member

    What are the before and after timings? Have you tested the impact on something other than a micro benchmark?

  5. JelleZijlstra commented on May 2, 2023

    @JelleZijlstra
    Member

    There appear to be no calls to PyObject_HasAttrString in CPython itself, other than internal extension modules. So it's unlikely there will be an effect on CPython's own performance. However, the function is part of the public API, so speeding it up may help some third-party extensions.

  6. itamaro commented on May 2, 2023

    @itamaro
    ContributorAuthor

    What are the before and after timings?

    the before and after numbers are quoted in the PR description (the optimization is about 3.3X speedup).

    Have you tested the impact on something other than a micro benchmark?

    as @JelleZijlstra pointed out, this doesn't really show up within cpython itself. it showed up in Instagram profiling data due to internal and/or third-party usage (I don't have the data available to pinpoint it).
    based on code search I see usage of this API in BoostPython & Cython for example.

  7. added a commit that references this issue on May 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coreperformancetype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions