Issue 26758: Unnecessary format string handling for no argument slot wrappers in typeobject.c (original) (raw)

Right now, in typeobject.c, the call_method and call_maybe utility functions have a fast path for no argument methods, where a NULL or "" format string just calls PyTuple_New(0) directly instead of wasting time parsing Py_VaBuildValue.

Problem is, nothing uses it. Every no arg user (the slot wrappers for len, index and next directly, and indirectly through the SLOT0 macro for neg, pos, abs, invert, int and float) is passing along "()" as the format string, which fails the test for NULL/"", so it calls Py_VaBuildValue that goes to an awful lot of trouble to scan the string a few times and eventually spit out the empty tuple anyway.

Changing the three direct calls to call_method where it passes "()" as the format string, as well as the definition of SLOT0, to replace "()" with NULL as the format string argument should remove a non-trivial number of C varargs function calls and string processing, replacing it with a single, cheap PyTuple_New(0) call (which Py_VaBuildValue was already eventually performing anyway). If I understand the purpose of these slot wrapper functions, that should give a free speed up to all types implemented at the Python level, particularly numeric types (e.g. fractions.Fraction) and container/iterator types (speeding up len and next respectively).

I identified this while on a work machine which I can't use to check out the Python repository; I'll submit a patch later today if no one else gets to it, once I'm home and can use my own computer to make/test the fix.