From 81db712f5e2ebb3119ec70491727baa24f50c7bd Mon Sep 17 00:00:00 2001 From: Cody Maloney Date: Sun, 22 Nov 2026 01:43:51 -0800 Subject: [PATCH] gh-162428: Use the freelist for exact complex() constructor results complex_subtype_from_c_complex() allocated through tp_alloc even for exact complex, so results of complex(...) never came from the complex freelist even though complex_dealloc() pushed them onto it. | Benchmark | main | branch | |-------------------------------------|:-------:|:---------------------:| | complex() | 20.9 ns | 16.3 ns: 1.29x faster | | complex(an_int) | 37.7 ns | 29.8 ns: 1.27x faster | | complex(a_float) | 31.5 ns | 25.4 ns: 1.24x faster | | complex(a_float, a_float) | 39.0 ns | 32.5 ns: 1.20x faster | | complex(a_str) | 49.6 ns | 42.1 ns: 1.18x faster | | complex(real=a_float, imag=a_float) | 70.5 ns | 63.1 ns: 1.12x faster | | complex(a_float, imag=a_float) | 63.4 ns | 56.7 ns: 1.12x faster | | complex(a_complex) | 20.2 ns | 19.3 ns: 1.04x faster | | SubComplex(a_float) | 41.4 ns | 40.6 ns: 1.02x faster | Not significant: float(a_float) (control). ```python3 import pyperf runner = pyperf.Runner() setup = """ class SubComplex(complex): pass a_float = 1.5; an_int = 3; a_complex = 1+2j; a_str = '1+2j' """ for stmt in [ "complex()", "complex(a_float)", "complex(an_int)", "complex(a_complex)", "complex(a_str)", "complex(a_float, a_float)", "complex(a_float, imag=a_float)", "complex(real=a_float, imag=a_float)", "SubComplex(a_float)", "float(a_float)", ]: runner.timeit(stmt, stmt, setup=setup) ``` Co-Authored-By: Claude Opus 5.5 --- Objects/complexobject.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Objects/complexobject.c b/Objects/complexobject.c index 4d2b5dc8e4613f3..8a8fc240dd80baf 100644 --- a/Objects/complexobject.c +++ b/Objects/complexobject.c @@ -415,6 +415,9 @@ complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { PyObject *op; + if (type == &PyComplex_Type) { + return PyComplex_FromCComplex(cval); + } op = type->tp_alloc(type, 0); if (op != NULL) ((PyComplexObject *)op)->cval = cval;