Skip to content

[3.13] GH-132380: Add optimization for non-interned type lookup. #132651

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 3.13
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -5219,11 +5219,66 @@ _PyTypes_AfterFork(void)
#endif
}

#ifdef Py_GIL_DISABLED
// Non-caching version of type lookup, containing a non-locking
// version of find_name_in_mro().
static PyObject *
type_lookup_non_interned(PyTypeObject *type, PyObject *name)
{
PyObject *mro = NULL;
Py_hash_t hash = _PyObject_HashFast(name);
if (hash == -1) {
goto error;
}

/* Keep a strong reference to mro because type->tp_mro can be replaced
during dict lookup, e.g. when comparing to non-string keys. */
mro = _PyType_GetMRO(type);
if (mro == NULL) {
assert(PyType_Ready(type));
goto error;
}

/* Look in tp_dict of types in MRO */
PyObject *res = NULL;
Py_ssize_t n = PyTuple_GET_SIZE(mro);
for (Py_ssize_t i = 0; i < n; i++) {
PyObject *base = PyTuple_GET_ITEM(mro, i);
PyObject *dict = lookup_tp_dict(_PyType_CAST(base));
assert(dict && PyDict_Check(dict));
if (_PyDict_GetItemRef_KnownHash((PyDictObject *)dict, name, hash, &res) < 0) {
goto error;
}
if (res != NULL) {
break;
}
}
Py_DECREF(mro);
return res;
error:
Py_XDECREF(mro);
return NULL;
}
#endif

/* Internal API to look for a name through the MRO.
This returns a borrowed reference, and doesn't set an exception! */
PyObject *
_PyType_LookupRef(PyTypeObject *type, PyObject *name)
{
#ifdef Py_GIL_DISABLED
// Bypass the type cache in this case since it is very unlikely it will do
// anything useful with a non-interned name lookup. This typically happens
// due to a getattr() call on a type with a name that has been constructed.
// We only have this path for the free-threaded build since cache misses are
// relatively more expensive for it and also to avoid contention on
// TYPE_LOCK. For the default build this extra branch is assumed to not be
// worth it, since this kind of lookup is quite rare.
if (!PyUnicode_CHECK_INTERNED(name) && _PyType_IsReady(type)) {
return type_lookup_non_interned(type, name);
}
#endif

PyObject *res;
int error;
PyInterpreterState *interp = _PyInterpreterState_GET();
Expand Down
Loading