Skip to content

Commit 81db712

Browse files
cmaloneyclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 51e0ff0 commit 81db712

1 file changed

Lines changed: 3 additions & 0 deletions

File tree

‎Objects/complexobject.c‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,9 @@ complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
415415
{
416416
PyObject *op;
417417

418+
if (type == &PyComplex_Type) {
419+
return PyComplex_FromCComplex(cval);
420+
}
418421
op = type->tp_alloc(type, 0);
419422
if (op != NULL)
420423
((PyComplexObject *)op)->cval = cval;

0 commit comments

Comments
 (0)