Skip to content

Poor thread scaling when constructing instances or accessing attributes #139103

Open

Description

@JukkaL

Bug report

Remaining scaling bugs

  • dataclass
  • namedtuple
  • enum

Bug description:

When constructing dataclass or NamedTuple instances on multiple threads (on a free threading build), or accessing enum class attributes, performance doesn't scale when using multiple threads.

Regular class example (scales well):

# b_regular_class.py
from threading import Thread
from time import time
import sys

class Foo:
    def __init__(self, x):
        self.x = x

niter = 5 * 1000 * 1000

def benchmark(n):
    for i in range(n):
        Foo(x=1)

for nth in (1, 4):
    t0 = time()
    threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print(f"{nth=} {(time() - t0) / nth}")

Dataclass example (doesn't scale well):

# b_dataclass.py
from threading import Thread
from dataclasses import dataclass
from time import time
import sys

@dataclass
class Foo:
    x: int

niter = 5 * 1000 * 1000

def benchmark(n):
    for i in range(n):
        Foo(x=1)

for nth in (1, 4):
    t0 = time()
    threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print(f"{nth=} {(time() - t0) / nth}")

Named tuple example (doesn't scale well):

# b_namedtuple.py
from threading import Thread
from typing import NamedTuple
from time import time
import sys

class Foo(NamedTuple):
    x: int

niter = 5 * 1000 * 1000

def benchmark(n):
    for i in range(n):
        Foo(x=1)

for nth in (1, 4):
    t0 = time()
    threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print(f"{nth=} {(time() - t0) / nth}")

Enum example (doesn't scale well):

# b_enum.py
from threading import Thread
from time import time
from enum import Enum
import sys

class Foo(Enum):
    X = 1
    Y = 2

niter = 5 * 1000 * 1000

def benchmark(n):
    for i in range(n):
        Foo.X
        Foo.Y.value

for nth in (1, 4):
    t0 = time()
    threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print(f"{nth=} {(time() - t0) / nth}")

Results on recent main branch (running on an EC2 instance):

(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_regular_class.py
nth=1 1.1085155010223389
nth=4 0.2796591520309448
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_dataclass.py
nth=1 1.1910037994384766
nth=4 1.0931583642959595
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_namedtuple.py
nth=1 1.5688557624816895
nth=4 2.0257126092910767
(cpython-dev) jukka@jukka-coder-dbx free-threading-benchmarks $ py b_enum.py
nth=1 0.9439797401428223
nth=4 2.272495985031128

The expected behavior is that when using 4 threads (nth=4), the elapsed time per benchmark iteration (the second printed value) goes down significantly compared to when using a single thread (nth=1), which happens with the first benchmark (b_regular_class.py) but not the others.

cc @colesbury (we discussed this at CPython Core Dev Sprint in person)

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. LindaSummer commented on Nov 21, 2025

    @LindaSummer
    Contributor

    Hi @colesbury ,

    Wish you a good day! 😊
    I have some findings about the Enum perf issue, and please correct me if I make a mistake in my analysis. 😊

    My guessing about the problem

    It should not be an issue directly related to Enum. It should be the descriptor's performance issue.

    My analysis steps

    Here is my configure for building cpython.

    ./configure --disable-gil \
        --prefix=$PWD/build-non-gil-release-perf-enabled \
        LDFLAGS="-Wl,-rpath=$PWD/build-non-gil-release-perf-enabled/lib" \
        CFLAGS="-g -fno-omit-frame-pointer"

    Construct two cases with only the descriptors' read/write

    The descriptor read

    The test case is below.

    from threading import Thread
    from time import time
    from enum import Enum
    
    niter = 5 * 1000 * 1000
    
    class BarDescriptor:
        def __get__(self, instance, owner):
            return 2
        
        def __setattr__(self, name, value):
            pass
    
    class Bar:
        X = BarDescriptor()
    
    def benchmark(n):
        for i in range(n):
            Bar.X
    
    for nth in (1, 4):
        t0 = time()
        threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print(f"{nth=} {(time() - t0) / nth}")

    I ran perf with below command. My filename is ./edward-test-descr-read.py.

    > perf record \                                                       
        -F 99 \
        -g \
        --call-graph dwarf,4096 \
    build-non-gil-release-perf-enabled/bin/python3 ./edward-test-descr-read.py
    nth=1 0.6697194576263428
    nth=4 1.6709617376327515
    
    [ perf record: Woken up 40 times to write data ]
    [ perf record: Captured and wrote 11.161 MB perf.data (2692 samples) ]
    
    > perf report --stdio --no-children --sort symbol --percent-limit 0.5 2>&1 | grep "^\s*[0-9]" | head -40
        27.26%  [.] _Py_DecRefShared                   -      -            
        24.72%  [.] _PyType_LookupStackRefAndVersion   -      -            
        14.08%  [.] _PyEval_Vector                     -      -            
         8.02%  [.] _PyFrame_ClearLocals               -      -            
         6.52%  [.] _Py_type_getattro_impl             -      -            
         6.45%  [.] _Py_NewRef                         -      -            
         4.38%  [.] _PyEval_EvalFrameDefault           -      -            
         3.61%  [.] slot_tp_descr_get                  -      -            
         1.55%  [.] PyObject_Vectorcall                -      -            
         0.82%  [.] initialize_locals                  -      -            
         0.60%  [.] _PyEvalFramePushAndInit            -      -            

    Here is the flamegraph.

    Image

    The descriptor write

    The test case is below. My test filename is ./edward-test-descr-write.py.

    from threading import Thread
    from time import time
    from enum import Enum
    
    niter = 5 * 1000 * 1000
    
    class BarDescriptor:
        def __get__(self, instance, owner):
            return 2
        
        def __setattr__(self, name, value):
            pass
    
    class Bar:
        X = BarDescriptor()
    
    def benchmark(n):
        items = [Bar()] * n
        for i in range(n):
            items[i].X = 1
    
    for nth in (1, 4):
        t0 = time()
        threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print(f"{nth=} {(time() - t0) / nth}")

    I ran perf command below.

    > perf record \    -F 99 \
        -g \
        --call-graph dwarf,4096 \
    build-non-gil-release-perf-enabled/bin/python3 ./edward-test-descr-write.py
    
    nth=1 0.4749176502227783
    nth=4 1.151348888874054
    [ perf record: Woken up 29 times to write data ]
    [ perf record: Captured and wrote 7.747 MB perf.data (1868 samples) ]
    
    > perf report --stdio --no-children --sort symbol --percent-limit 0.5 2>&1 | grep "^\s*[0-9]" | head -40
        63.96%  [.] _PyObject_GenericSetAttrWithDict       -      -            
        19.26%  [.] _PyType_LookupStackRefAndVersion       -      -            
         7.23%  [.] _PyObject_StoreInstanceAttribute       -      -            
         2.42%  [.] _PyEval_EvalFrameDefault               -      -            
         1.49%  [.] _PyCriticalSection_End                 -      -            
         1.24%  [.] PyObject_SetAttr                       -      -            
         1.19%  [.] list_repeat                            -      -            
         0.58%  [.] _Py_Dealloc                            -      -            

    Here is the flamegraph file.

    Image

    My analysis conjecture

    It seems that the _PyType_LookupStackRefAndVersion is the bottleneck.

    I check its implementation and find it seems waiting for all threads in non-gil mode

    cpython/Objects/typeobject.c

    Lines 6120 to 6214 in 49ff8b6

    unsigned int
    _PyType_LookupStackRefAndVersion(PyTypeObject *type, PyObject *name, _PyStackRef *out)
    {
    unsigned int h = MCACHE_HASH_METHOD(type, name);
    struct type_cache *cache = get_type_cache();
    struct type_cache_entry *entry = &cache->hashtable[h];
    #ifdef Py_GIL_DISABLED
    // synchronize-with other writing threads by doing an acquire load on the sequence
    while (1) {
    uint32_t sequence = _PySeqLock_BeginRead(&entry->sequence);
    uint32_t entry_version = _Py_atomic_load_uint32_acquire(&entry->version);
    uint32_t type_version = _Py_atomic_load_uint32_acquire(&type->tp_version_tag);
    if (entry_version == type_version &&
    _Py_atomic_load_ptr_relaxed(&entry->name) == name) {
    OBJECT_STAT_INC_COND(type_cache_hits, !is_dunder_name(name));
    OBJECT_STAT_INC_COND(type_cache_dunder_hits, is_dunder_name(name));
    if (_Py_TryXGetStackRef(&entry->value, out)) {
    // If the sequence is still valid then we're done
    if (_PySeqLock_EndRead(&entry->sequence, sequence)) {
    return entry_version;
    }
    PyStackRef_XCLOSE(*out);
    }
    else {
    // If we can't incref the object we need to fallback to locking
    break;
    }
    }
    else {
    // cache miss
    break;
    }
    }
    #else
    if (entry->version == type->tp_version_tag && entry->name == name) {
    assert(type->tp_version_tag);
    OBJECT_STAT_INC_COND(type_cache_hits, !is_dunder_name(name));
    OBJECT_STAT_INC_COND(type_cache_dunder_hits, is_dunder_name(name));
    *out = entry->value ? PyStackRef_FromPyObjectNew(entry->value) : PyStackRef_NULL;
    return entry->version;
    }
    #endif
    OBJECT_STAT_INC_COND(type_cache_misses, !is_dunder_name(name));
    OBJECT_STAT_INC_COND(type_cache_dunder_misses, is_dunder_name(name));
    /* We may end up clearing live exceptions below, so make sure it's ours. */
    assert(!PyErr_Occurred());
    // We need to atomically do the lookup and capture the version before
    // anyone else can modify our mro or mutate the type.
    PyObject *res;
    int error;
    PyInterpreterState *interp = _PyInterpreterState_GET();
    int has_version = 0;
    unsigned int assigned_version = 0;
    BEGIN_TYPE_LOCK();
    // We must assign the version before doing the lookup. If
    // find_name_in_mro() blocks and releases the critical section
    // then the type version can change.
    if (MCACHE_CACHEABLE_NAME(name)) {
    has_version = assign_version_tag(interp, type);
    assigned_version = type->tp_version_tag;
    }
    res = find_name_in_mro(type, name, &error);
    END_TYPE_LOCK();
    /* Only put NULL results into cache if there was no error. */
    if (error) {
    /* It's not ideal to clear the error condition,
    but this function is documented as not setting
    an exception, and I don't want to change that.
    E.g., when PyType_Ready() can't proceed, it won't
    set the "ready" flag, so future attempts to ready
    the same type will call it again -- hopefully
    in a context that propagates the exception out.
    */
    if (error == -1) {
    PyErr_Clear();
    }
    *out = PyStackRef_NULL;
    return 0;
    }
    if (has_version) {
    #if Py_GIL_DISABLED
    update_cache_gil_disabled(entry, name, assigned_version, res);
    #else
    PyObject *old_value = update_cache(entry, name, assigned_version, res);
    Py_DECREF(old_value);
    #endif
    }
    *out = res ? PyStackRef_FromPyObjectSteal(res) : PyStackRef_NULL;
    return has_version ? assigned_version : 0;
    }

    My guessing of the performance issue

    I plan to research the _PyType_LookupStackRefAndVersion function and try to find a solution.

    But I'm not sure whether my analysis and solution direction are correct.

    Please help correct me on my report if there is any mistake. 😊

    Thanks very much!

    Best Regards,
    Edward

  2. colesbury commented on Nov 21, 2025

    @colesbury
    Contributor

    The setter for a descriptor is __set__, not __setattr__. I think you are setting the instance attribute in your benchmark, not invoking the descriptor.

  3. LindaSummer commented on Nov 22, 2025

    @LindaSummer
    Contributor

    The setter for a descriptor is __set__, not __setattr__. I think you are setting the instance attribute in your benchmark, not invoking the descriptor.

    Hi @colesbury ,

    Thanks very much for your correction! ❤
    I will try to continue investigating this problem.

    Best Regards,
    Edward

  4. LindaSummer commented on Nov 30, 2025

    @LindaSummer
    Contributor

    Hi @colesbury ,

    Sorry to bother you again.

    I have some new findings that the __set__ performance is improved to a good result, but the descriptor __get__ issue still exists and is mitigated by the case that confused me.

    I want to get some suggestions from you.

    Here is my testing patch LindaSummer@4737a45 .

    I added code below in both _PyObject_GenericGetAttrWithDict and _PyObject_GenericSetAttrWithDict.

    Below are test cases and test results in main and my test branch.

    I have used a new computer with better performance, so the baseline result improved compared to my previous testing in the above conversation.

    __set__ test

    Test case:

    from threading import Thread
    from time import time
    from enum import Enum
    
    niter = 5 * 1000 * 1000
    
    class BarDescriptor:
        def __get__(self, instance, owner):
            return None
        
        def __set__(self, instance, value):
            pass
    
    class Bar:
        X = BarDescriptor()
    
    def benchmark(n):
        items = [Bar()] * n
        for i in range(n):
            items[i].X = 1
    
    for nth in (1, 4):
        t0 = time()
        threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print(f"{nth=} {(time() - t0) / nth}")

    Result without my patch.

    nth=1 0.2444922924041748
    nth=4 0.534302294254303
    

    Result with my patch.

    nth=1 0.23746991157531738
    nth=4 0.15026915073394775
    

    The performance has improved significantly.

    __get__ test

    Test case:

    from threading import Thread
    from time import time
    from enum import Enum
    
    niter = 5 * 1000 * 1000
    
    class BarDescriptor:
        def __get__(self, instance, owner):
            return None
        
        def __set__(self, instance, value):
            pass
    
    class Bar:
        X = BarDescriptor()
    
    def benchmark(n):
        # items = [Bar()] * n
        # items[0].X = 1  # Warm up
        for i in range(n):
            Bar.X
    
    for nth in (1, 4):
        t0 = time()
        threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print(f"{nth=} {(time() - t0) / nth}")

    Result without my patch.

    nth=1 0.24678421020507812
    nth=4 0.6124725937843323
    

    Result in my test branch.

    nth=1 0.23792409896850586
    nth=4 0.6084508895874023
    

    But when I uncommented the two-line warm-up codes, the performance improved.

    nth=1 0.21433663368225098
    nth=4 0.39008378982543945
    

    It seems the performance improvement is 1x.

    I'm not sure the root cause of the __get__ and whether my patch for __set__ is good.

    Hope to get a suggestion from you!

    Wish you a good day!

    Best Regards,
    Edward

  5. added a commit that references this issue on Dec 6, 2025
  6. LindaSummer commented on Dec 6, 2025

    @LindaSummer
    Contributor

    Hi @colesbury ,

    I have some findings on this problem and want to get some guidance of the solution.

    Please correct me if I made any mistake. 😊

    My temporay patch to prove my guessing

    After going through the code and debugging, I find that the difference between a descriptor getter and a regular class is here.

    cpython/Objects/typeobject.c

    Lines 6381 to 6391 in 5be3405

    meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
    if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
    /* Data descriptors implement tp_descr_set to intercept
    * writes. Assume the attribute is not overridden in
    * type's tp_dict (and bases): call the descriptor now.
    */
    res = meta_get(meta_attribute, (PyObject *)type,
    (PyObject *)metatype);
    Py_DECREF(meta_attribute);
    return res;

    So the performance downgrade should be caused be the meta_get.
    It is the slot_tp_descr_get when this callback invoked.

    cpython/Objects/typeobject.c

    Lines 10837 to 10860 in 5be3405

    static PyObject *
    slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
    {
    PyTypeObject *tp = Py_TYPE(self);
    PyObject *get;
    get = _PyType_LookupRef(tp, &_Py_ID(__get__));
    if (get == NULL) {
    #ifndef Py_GIL_DISABLED
    /* Avoid further slowdowns */
    if (tp->tp_descr_get == slot_tp_descr_get)
    tp->tp_descr_get = NULL;
    #endif
    return Py_NewRef(self);
    }
    if (obj == NULL)
    obj = Py_None;
    if (type == NULL)
    type = Py_None;
    PyObject *stack[3] = {self, obj, type};
    PyObject *res = PyObject_Vectorcall(get, stack, 3, NULL);
    Py_DECREF(get);
    return res;
    }

    But as we could see here at the end of the function, it invokes Py_DECREF(get);.

    The type cache in _PyType_LookupRef works well.
    But in free threading senario, we probably don't in same thread with the creator of type.
    So it goes into the loop heavily.

    cpython/Objects/object.c

    Lines 370 to 404 in 5be3405

    // Decrement the shared reference count of an object. Return 1 if the object
    // is dead and should be deallocated, 0 otherwise.
    static int
    _Py_DecRefSharedIsDead(PyObject *o, const char *filename, int lineno)
    {
    // Should we queue the object for the owning thread to merge?
    int should_queue;
    Py_ssize_t new_shared;
    Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&o->ob_ref_shared);
    do {
    should_queue = (shared == 0 || shared == _Py_REF_MAYBE_WEAKREF);
    if (should_queue) {
    // If the object had refcount zero, not queued, and not merged,
    // then we enqueue the object to be merged by the owning thread.
    // In this case, we don't subtract one from the reference count
    // because the queue holds a reference.
    new_shared = _Py_REF_QUEUED;
    }
    else {
    // Otherwise, subtract one from the reference count. This might
    // be negative!
    new_shared = shared - (1 << _Py_REF_SHARED_SHIFT);
    }
    #ifdef Py_REF_DEBUG
    if ((new_shared < 0 && _Py_REF_IS_MERGED(new_shared)) ||
    (should_queue && is_dead(o)))
    {
    _Py_NegativeRefcount(filename, lineno, o);
    }
    #endif
    } while (!_Py_atomic_compare_exchange_ssize(&o->ob_ref_shared,
    &shared, new_shared));

    I use below patch to disable the decref and the result imrpoved about 1.3x comapring to current performance.

    diff --git a/Objects/typeobject.c b/Objects/typeobject.c
    index 4c6ff51493..419e784748 100644
    --- a/Objects/typeobject.c
    +++ b/Objects/typeobject.c
    @@ -10855,7 +10855,7 @@ slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
             type = Py_None;
         PyObject *stack[3] = {self, obj, type};
         PyObject *res = PyObject_Vectorcall(get, stack, 3, NULL);
    -    Py_DECREF(get);
    +    // Py_DECREF(get);
         return res;
     }

    Here is my test sample.

    from threading import Thread
    from time import time
    
    niter = 5 * 1000 * 10000
    
    class BarDescriptor:
        def __get__(self, instance, owner):
            return None
    
        def __set__(self, instance, value):
            pass
    
    
    class SimpleClass:
        pass
    
    
    class Bar:
        X = BarDescriptor()
    
    def benchmark(n):
        for i in range(n):
            Bar.X
    
    for nth in (1, 4):
        t0 = time()
        threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print(f"{nth=} {(time() - t0) / nth}")

    Before applied the temporary patch, below is the result.

    ➜ ./python edward-test-enum.py
    nth=1 2.4528021812438965
    nth=4 5.816055417060852
    

    After applied the patch, below is the result.

    ➜ ./python edward-test-enum.py
    nth=1 2.181805372238159
    nth=4 4.480860769748688
    

    We could see it improved a little.

    My investogation for the behavior.

    Perf report

    First I run with perf and got below flamegraph.

    Image

    We cloud find below samples in slot_tp_descr_get.

    Image

    We could find that it cost a lot of time in slot_tp_descr_get -> Py_DECREF -> _Py_DecRefShared -> _Py_DecRefSharedDebug -> _Py_DecRefSharedIsDead -> _Py_atomic_compare_exchange_ssize.

    This is the bottleneck in the decrement for non-local objects.

    PyStats

    I enabled statistics in build and get below diff for a SimpleClass and a BarDescriptor.

    Here are my test code.

    from threading import Thread
    from time import time
    
    niter = 5 * 1000 * 10000
    
    class BarDescriptor:
        def __get__(self, instance, owner):
            return None
    
        def __set__(self, instance, value):
            pass
    
    
    class SimpleClass:
        pass
    
    
    class Bar:
        X = BarDescriptor()
       ## Use SimpleClass for another test
       # X = SimpleClass()
    
    def benchmark(n):
        for i in range(n):
            Bar.X
    
    for nth in (1, 4):
        t0 = time()
        threads = [Thread(target=benchmark, args=(niter,)) for _ in range(nth)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        print(f"{nth=} {(time() - t0) / nth}")

    Below is the diff i found in the two cases.

    ➜ diff descr-stat.output simple-stat.output
    4,5d3
    < opcode[CACHE].pair_count[RESUME] : 1
    < opcode[CACHE].pair_count[RESUME_CHECK] : 49999999
    9d6
    <     opcode[INTERPRETER_EXIT].execution_count : 50000000
    17,18d13
    <     opcode[RETURN_VALUE].execution_count : 50000000
    < opcode[RETURN_VALUE].pair_count[INTERPRETER_EXIT] : 50000000
    48,49d42
    <     opcode[LOAD_CONST].execution_count : 50000000
    < opcode[LOAD_CONST].pair_count[RETURN_VALUE] : 50000000
    66,68d58
    <     opcode[RESUME].execution_count : 2
    < opcode[RESUME].pair_count[LOAD_CONST] : 1
    < opcode[RESUME].pair_count[RESUME] : 1
    74,76c64
    <     opcode[RESUME_CHECK].execution_count : 49999999
    < opcode[RESUME_CHECK].pair_count[LOAD_CONST] : 49999999
    < Calls to PyEval_EvalDefault: 50000000
    ---
    > Calls to PyEval_EvalDefault: 0
    78c66
    < Frames pushed: 50000000
    ---
    > Frames pushed: 0
    80,81c68,69
    < Calls via PyEval_EvalFrame[0] : 50000000
    < Calls via PyEval_EvalFrame[1] : 50000000
    ---
    > Calls via PyEval_EvalFrame[0] : 0
    > Calls via PyEval_EvalFrame[1] : 0
    84c72
    < Calls via PyEval_EvalFrame[4] : 50000000
    ---
    > Calls via PyEval_EvalFrame[4] : 0
    92,93c80,81
    < Object allocations: 5
    < Object allocations to 512 bytes: 5
    ---
    > Object allocations: 4
    > Object allocations to 512 bytes: 4
    98c86
    < Object interpreter mortal increfs: 50000000
    ---
    > Object interpreter mortal increfs: 0
    100,105c88,93
    < Object mortal increfs: 100012225
    < Object mortal decrefs: 100012225
    < Object interpreter immortal increfs: 50000000
    < Object interpreter immortal decrefs: 50001027
    < Object immortal increfs: 12
    < Object immortal decrefs: 9
    ---
    > Object mortal increfs: 50012224
    > Object mortal decrefs: 12224
    > Object interpreter immortal increfs: 0
    > Object interpreter immortal decrefs: 1027
    > Object immortal increfs: 11
    > Object immortal decrefs: 8
    113,114c101,102
    < Object method cache dunder hits: 49999999
    < Object method cache dunder misses: 1
    ---
    > Object method cache dunder hits: 0
    > Object method cache dunder misses: 0

    We could find that the below unexpected behavior.

    Object interpreter mortal increfs: 50000000
    Object mortal increfs: 100012225
    Object mortal decrefs: 100012225
    

    As we could see the cache works well.

    Object method cache dunder hits: 49999999
    Object method cache dunder misses: 1
    

    My conculsion

    I think that we should have a way to borrow a reference of get rather than directly increment and decrement it.
    But I have no good idea for this.

    Could you give me some suggestions and correct me if I made any mistakes? 😊

    Wish you a good day!

    Best Regards,
    Edward

  7. added a commit that references this issue on Dec 8, 2025
  8. added 3 commits that reference this issue on Jan 29, 2026
  9. added a commit that references this issue on Feb 3, 2026
  10. added a commit that references this issue on Feb 3, 2026
  11. added 4 commits that reference this issue on Feb 3, 2026
  12. added 3 commits that reference this issue on Feb 15, 2026
  13. added a commit that references this issue on Feb 18, 2026
  14. added a commit that references this issue on Apr 25, 2026
  15. johng commented on Aug 16, 2026

    @johng
    Contributor

    Also see this on various class/instance attributes in addition to the above PR, shall I be putting these in a new issue?

    class MyClassWithInstanceAttr:
        def __init__(self):
            self.attr = object()
    
    # A single instance shared between threads. Reading its attribute (stored in
    # the inline __dict__ values, LOAD_ATTR_INSTANCE_VALUE) contends on the shared
    # value's reference count on every read.
    _shared_instance = MyClassWithInstanceAttr()
    
    @register_benchmark
    def shared_instance_attribute():
        obj = _shared_instance
        for _ in range(1000 * WORK_SCALE):
            obj.attr
            obj.attr
            obj.attr
    

    ./python_main.exe Tools/ftscalingbench/ftscalingbench.py shared_instance_attribute
    Running benchmarks with 18 threads
    shared_instance_attribute 25.0x slower

  16. added a commit that references this issue on Oct 15, 2026
  17. johng commented on Nov 20, 2026

    @johng
    Contributor

    @eendebakpt would you mind mind taking a look at the above, thanks!

  18. added a commit that references this issue on Nov 22, 2026
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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions