Skip to content

Commit ac82d36

Browse files
authored
optimize PyType_GetBaseByToken()
1 parent ac03429 commit ac82d36

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

Objects/typeobject.c

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5293,42 +5293,53 @@ get_base_by_token_recursive(PyTypeObject *type, void *token)
52935293
}
52945294

52955295
static inline int
5296-
_token_found(PyTypeObject *type, PyTypeObject **result)
5296+
_token_found(PyTypeObject **result, PyTypeObject *type)
52975297
{
52985298
if (result != NULL) {
52995299
*result = (PyTypeObject *)Py_NewRef(type);
53005300
}
53015301
return 1;
53025302
}
53035303

5304+
// Prefer this to gotos for optimization
5305+
static inline int
5306+
_token_not_found(PyTypeObject **result, int ret)
5307+
{
5308+
assert(-1 <= ret && ret <= 0);
5309+
if (result != NULL) {
5310+
*result = NULL;
5311+
}
5312+
return ret;
5313+
}
5314+
53045315
int
53055316
PyType_GetBaseByToken(PyTypeObject *type, void *token, PyTypeObject **result)
53065317
{
53075318
if (token == NULL) {
53085319
PyErr_Format(PyExc_SystemError,
53095320
"PyType_GetBaseByToken called with token=NULL");
5310-
goto error;
5321+
return _token_not_found(result, -1);
53115322
}
53125323
if (!PyType_Check(type)) {
53135324
PyErr_Format(PyExc_TypeError,
53145325
"expected a type, got a '%T' object", type);
5315-
goto error;
5326+
return _token_not_found(result, -1);
53165327
}
53175328
if (!_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
53185329
// Static type MRO contains no heap type,
53195330
// which type_ready_mro() ensures.
5320-
goto not_found;
5331+
return _token_not_found(result, 0);
53215332
}
53225333
if (((PyHeapTypeObject*)type)->ht_token == token) {
5323-
return _token_found(type, result);
5334+
return _token_found(result, type);
53245335
}
53255336
PyObject *mro = type->tp_mro;
53265337
if (mro == NULL) {
53275338
PyTypeObject *base = get_base_by_token_recursive(type, token);
53285339
if (base != NULL) {
5329-
return _token_found(base, result);
5340+
return _token_found(result, base);
53305341
}
5331-
goto not_found;
5342+
return _token_not_found(result, 0);
53325343
}
53335344
assert(PyTuple_Check(mro));
53345345
// mro_invoke() ensures that the type MRO cannot be empty.
@@ -5343,19 +5354,10 @@ PyType_GetBaseByToken(PyTypeObject *type, void *token, PyTypeObject **result)
53435354
continue;
53445355
}
53455356
if (((PyHeapTypeObject*)base)->ht_token == token) {
5346-
return _token_found(base, result);
5357+
return _token_found(result, base);
53475358
}
53485359
}
5349-
not_found:
5350-
if (result != NULL) {
5351-
*result = NULL;
5352-
}
5353-
return 0;
5354-
error:
5355-
if (result != NULL) {
5356-
*result = NULL;
5357-
}
5358-
return -1;
5360+
return _token_not_found(result, 0);
53595361
}
53605362

53615363

0 commit comments

Comments
 (0)