Skip to content

Commit 6fb51f2

Browse files
johngclaude
andauthored
gh-154401: Skip fetching the thread state for non-GC types in _Py_Dealloc (GH-154430)
_Py_Dealloc() fetched the current thread state and computed the C recursion margin on every deallocation, but both are only used by the trashcan mechanism, which applies only to GC-tracked types. Gate them behind the Py_TPFLAGS_HAVE_GC check so the common non-GC case (int, float, str and similar atomic types) skips them. On platforms where _PyThreadState_GET() reads a _Thread_local via a function call (e.g. macOS TLV), this removes a call from every non-GC deallocation. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent a2a8466 commit 6fb51f2

2 files changed

Lines changed: 15 additions & 6 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Slightly speed up deallocation of objects that are not tracked by the garbage
2+
collector, such as :class:`int`, :class:`float` and :class:`str`.

Objects/object.c

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3292,13 +3292,20 @@ _Py_Dealloc(PyObject *op)
32923292
PyTypeObject *type = Py_TYPE(op);
32933293
unsigned long gc_flag = type->tp_flags & Py_TPFLAGS_HAVE_GC;
32943294
destructor dealloc = type->tp_dealloc;
3295-
PyThreadState *tstate = _PyThreadState_GET();
3296-
intptr_t margin = _Py_RecursionLimit_GetMargin(tstate);
3297-
if (margin < 2 && gc_flag) {
3298-
_PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3299-
return;
3295+
PyThreadState *tstate = NULL;
3296+
intptr_t margin = 0;
3297+
if (gc_flag) {
3298+
tstate = _PyThreadState_GET();
3299+
margin = _Py_RecursionLimit_GetMargin(tstate);
3300+
if (margin < 2) {
3301+
_PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3302+
return;
3303+
}
33003304
}
33013305
#ifdef Py_DEBUG
3306+
if (tstate == NULL) {
3307+
tstate = _PyThreadState_GET();
3308+
}
33023309
#if !defined(Py_GIL_DISABLED) && !defined(Py_STACKREF_DEBUG)
33033310
/* This assertion doesn't hold for the free-threading build, as
33043311
* PyStackRef_CLOSE_SPECIALIZED is not implemented */
@@ -3340,7 +3347,7 @@ _Py_Dealloc(PyObject *op)
33403347
Py_XDECREF(old_exc);
33413348
Py_DECREF(type);
33423349
#endif
3343-
if (tstate->delete_later && margin >= 4 && gc_flag) {
3350+
if (gc_flag && tstate->delete_later && margin >= 4) {
33443351
_PyTrash_thread_destroy_chain(tstate);
33453352
}
33463353
}

0 commit comments

Comments
 (0)