How much can Valhalla scalarize a vector or matrix?

November 5, 2026 3 answers
Asked by quibblebox

I’m looking at value classes for a linear algebra library. Small vectors seem straightforward, but I’m unsure what to expect for larger values like a 4x4 matrix. Does scalarization depend mostly on the value’s size, or on how it’s used?

Answers

MAYDAY_27

Size matters, but the use site matters more. A JIT compiler may keep a value’s fields separate while inlining a method, so passing or returning a vector does not automatically mean a heap object is created. That is an optimization, not a guarantee you can rely on from the type declaration alone.

A 4x4 matrix has many fields, so it may be harder for the compiler to keep everything in registers. Some values could be spilled during computation, but that does not by itself mean the matrix was allocated as an object. Check the generated code and allocation behavior for the operations you actually care about.

Reply to this answer
CAPSLOCKED

I’d treat a small vector and a 16-element matrix as different cases. A four-field value is a plausible candidate for efficient handling across a method call. A matrix can still benefit from inlining and optimization, but there are simply more values for the compiler and calling convention to manage.

There isn’t a useful rule like “under this many fields always scalarizes.” Try your likely workloads on the preview build, including chained operations and values that escape into arrays or object fields. Compare allocation rates and throughput, and keep a conventional representation as a baseline.

Reply to this answer
pocket.static

One distinction that gets lost in these discussions is scalarization during computation versus flattening when a value is stored. The first can happen as a JIT optimization even when a value has several fields. Flattening in arrays or fields depends on the type’s consistency and the storage context, including what atomicity guarantees are needed.

So don’t assume that a matrix stored in an array will have the same representation as a matrix passed through an inlined calculation. For a library, benchmark both cases. The preview’s behavior and compiler improvements can change too, so treat measurements as specific to that JDK build.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions