Skip to content

Native copies of int, float and complex for C extensions - #24

Draft
Ivo Horák (horakivo) wants to merge 5 commits into
developfrom
perf/native-numbers
Draft

Ivo Horák (horakivo) wants to merge 5 commits into
developfrom
perf/native-numbers

Conversation

@horakivo

@horakivo Ivo Horák (horakivo) commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Draft, do not merge. Stacked on #21 (perf/capi-fast-paths). This is the numeric half of #22, split out so it can be measured and reviewed without the string half.

What it does

When C asks for an int, float or complex, it gets a native struct with CPython's layout that holds a copy of the value, instead of a stub for the Java object. C reads the value directly, and the copy needs no entry in the handle table and no weak reference.

  • 211eaee7: the native copies for int, float and complex.
  • 54223a2c: free-list links written with memcpy (strict aliasing).
  • 74e80002: the check of released argument tuples compares values for these types.
  • 507a3ea6: removes the opt-in native layout experiment.
  • 480a1571: no extra fields on complex; see the limits below.

What it leaves out, compared with #22

The native copies of str and everything that only exists for them. Strings have an open trade-off between identity through containers and memory (see #22); numbers do not.

Known limits

  • A copy handed out as a borrowed reference is valid until the outermost C call returns.
  • 480a1571 changes what is means for exact complex numbers: they compare by value, the way GraalPy already treats floats, so complex(1, 2) is complex(1, 2) is True (it is False on CPython and was False here). In exchange a complex object carries no extra fields; before this commit every complex was 24 bytes larger, also in pure Python code. l[0] is c after l = [c] stays true. If strict identity is preferred, the alternative is one pointer field per complex (8 bytes); the commit can be dropped on its own.
  • 507a3ea6 removes an opt-in experiment (__native_layout__ on a class with __slots__) that came with the first commit, including a bytecode fast path for stores to __slots__ attributes. After it, the bytecode interpreter is identical to the base.

Measured

One benchmark run of 480a157 against three runs of the base, median iteration time on the benchmark host (geometric mean of the ratios, below 1 is faster): real packages 1.00, C API micro 0.79, pure Python 0.99.

  • Much faster: c-many-shortlived-objs 24.5 to 30.9 s down to 2.1 s, c-arith-binop2 3.2 to 3.6 s down to 0.32 s, c-arith-binop 4.7 s down to 1.3 s.
  • Slower by 5 to 18%: nine C API micro rows that pass no numbers to C (c-list-iterating-obj 0.74 to 0.87 s, c-magic-iter 3.24 to 3.67 s, c-magic-bool, c-call-method-noargs, both c-issubtype rows and others).
  • c-arith-binop peak RSS 483 MB to 1,553 MB.
  • No package row gains. lxml-xpath is 1.84 to 1.93 s on the base and 2.19 s here (one run).
  • mandelbrot3 is within the base's range, so the extra bytes on complex were the cause of the slowdown seen on Native copies of int, float, complex and str for C extensions #22.

So on its own this half pays off only where C code handles many numbers one object at a time, and it has a cost on calls that do not involve numbers at all.

Testing

Assertions build on macOS: all 758 C API tests pass (9 skipped), and 1,854 tagged standard-library tests (test_capi, test_float, test_long, test_complex, test_str, test_struct, test_array, test_json, test_pyexpat) pass, the same as on the base commit. Elide CI (Linux x86-64, assertions on) passes on 480a157.

🤖 Generated with Claude Code

Values that cross into C no longer always get a Java wrapper plus a native
stub.

Shared native state (NativeComplex): one native block holds the
allocators that C and Java share without upcalls, the borrowed-reference
stack and the downcall depth. Generated downcall invokers (and vectorcall
slot calls) enter and leave the depth; when the outermost downcall
returns, the counts on the borrowed stack are dropped.

- complex: an exact complex is passed to C as a native PyComplexObject
  from a size-class allocator. A list of exact complex values stores
  counted pointers to such structs (ComplexPtrSequenceStorage); PComplex
  keeps an unowned pointer and serial so a value read from such a list is
  the same object when stored or passed again. PyComplex_FromDoubles and
  exact complex allocation/deallocation in C use the same allocator.
- int: an exact int that does not fit the tagged pointer (up to 120 bits)
  is passed as a native PyLongObject with no Java companion; the Java
  value stays a long. PyLong_From*/PyLong_As* handle these in C.
- float: an exact float that cannot be tagged is passed as a native
  PyFloatObject from a 64-byte small-block pool that PyObject_Malloc and
  Java share. An instance of a static native float subclass that is only
  (type, ob_fval) is held in Java as a value copy (PNativeFloat) instead of
  a native object with a weak reference and lookup entry.

Lifetime: a copy passed as an argument or borrowed result holds a count on
the borrowed stack until the outermost C call returns; C that increfs it
keeps it. Items that a container holds (dict and list items, PyDict_Next)
are still promoted to objects with stable stubs, as before. A copy that C
keeps without its own reference past the outermost call is freed under it.

Also included, experimental and opt-in: classes with __slots__ that set
__native_layout__ = True (and derive directly from object) get instances
whose slots live in native reference-counted structs, with a
pointer-aware list storage for them and pins on dict, cell, global and
attribute stores. No class in the standard library or the tests sets it.
The pins, the list storage and the struct paths are guarded by an
assumption that holds until such a class is created. What runs for every
program: a bytecode fast path for stores to __slots__ attributes (shape-
cached, like the existing load fast path), and a profiled
"native instance" type check on slot reads and writes.

__graalpython__ gains measurement helpers: complex_counters,
native_long_live, slots_counters (counters need -Dgraalpy.complexCounters
or -Dgraalpy.slotsCounters) and native_quiesce.
…ith memcpy

GCC rejects the previous cast of the value field's address to a block pointer under -Werror=strict-aliasing. Clang accepted it. The stored bytes are the same.
ReleaseNativeArgsTupleNode asserted (with detailed assertions) that every
element of the args tuple is still the pointer that converting the managed
argument again yields. That holds for stubs, handles and tagged values,
but not for arguments that cross as native value copies (int, float,
complex): each conversion makes a new struct, so the check failed for
correct tuples, and the conversion done by the check itself allocated a
further copy.

For an element that is a value copy, compare the struct's type and value
with the managed argument (value for int, raw bits for float and complex,
type and bits for value-type float subclasses) and require that it is
still alive; other elements keep the pointer check.
@horakivo Ivo Horák (horakivo) added the perf:bench Runs walltime bench on our infra label Nov 28, 2026
The commit that copies exact complex, int and float values to native
structs also carried an inactive experiment: classes with __slots__ that
set __native_layout__ = True got instances whose slots live in native
reference-counted structs, with a pointer-aware list storage for them and
pins on dict, cell, global and attribute stores. Nothing sets that
attribute, and none of it is needed by the value copies, so it is removed:

- PNativeLayoutObject, NativeInstance, NativeSlotNodes and
  InstPtrSequenceStorage, and the InstPtr storage type;
- the instance-word kind of ComplexPtrSequenceStorage, which now holds
  complex pointers only, and the InstPtr specializations in the sequence
  storage nodes and list literals;
- the pins in PCell, DynamicObjectStorage, ObjectHashMap, the attribute,
  global and name writes and ObjectSequenceStorage, the native-layout
  object.__new__, hash, id and slot descriptor paths, the class
  registration in TypeNodes and the class id in PythonClass;
- the native-layout branches of the bytecode slot read fast path, the slot
  store fast path that came with them, and the all-None list literal path;
- the "is" specialization for native-layout instances and the
  native_quiesce and slots_counters builtins.
PComplex had three extra fields for the native copies: an exact-type flag
and the pointer and serial of the struct it was last stored to or read
from. They made every complex object 24 bytes larger, including the many
temporaries of pure-Python complex arithmetic that never reach native
memory, and pure-Python complex code allocated correspondingly more.

The exact-type flag is now derived from the object's class. The pointer
and serial served two purposes: storing the same complex object again
reused its struct, and two values read from the same struct were "is"
each other. A store now always makes a new struct, and exact complex
numbers compare by value under "is", like floats already do, so values
read from a list of complex numbers are still identical to what was
stored. As with floats, two equal exact complex numbers created
independently are now "is" each other.
@datadog-official

This comment has been minimized.

@horakivo
Ivo Horák (horakivo) changed the base branch from perf/capi-fast-paths to develop November 29, 2026 00:55
@codspeed

codspeed Bot commented Nov 29, 2026

Copy link
Copy Markdown

Merging this PR will regress 2 benchmarks

1 warning

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚡ 8 improved benchmarks
❌ 2 regressed benchmarks
✅ 56 untouched benchmarks
⏩ 21 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ micro-native/c-magic-iter[50000000] 2.8 s 3.3 s -16.1%
❌ micro-native/c-call-method-o[5000000] 72.7 ms 81.4 ms -10.73%
⚡ micro-native/c-many-shortlived-objs[100000000] 24.1 s 2 s ×12
⚡ micro-native/c-arith-binop2[100] 3,183.2 ms 318.7 ms ×10
⚡ micro-native/c-arith-binop[1000] 4.7 s 1.3 s ×3.6
⚡ micro-native/c-upcall-slot[1048576] 1.8 ms 1.5 ms +16.92%
⚡ packages/pandas-str[20000] 993.3 ms 866.1 ms +14.69%
⚡ micro-native/c-upcall-builtin-function[67108864] 146.5 ms 130.2 ms +12.51%
⚡ micro-native/c-call-method[5000000] 476.5 ms 427.2 ms +11.54%
⚡ meso/chaos-sized2[500] 934.9 ms 843.3 ms +10.86%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing perf/native-numbers (480a157) with develop (55fc469)2

Open in CodSpeed

Footnotes

  1. 21 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on develop (bda697c) during the generation of this report, so 55fc469 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf:bench Runs walltime bench on our infra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant