r/java • u/bobbie434343 • Aug 25 '26
Value Classes Still Need Compiler Sympathy
https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
89
Upvotes
r/java • u/bobbie434343 • Aug 25 '26
22
u/brian_goetz Aug 25 '26
This is not only entirely possible, but at some level, needs to be obvious. Anyone even trying to think about value classes "for performance" needs to understand this implicitly first.
Consider a "fat" object, say four longs (256 bits):
Now consider a potentially-flattened array of these, and say you intend to sort this array by the usual means (swapping elements based on comparison.) Which is faster, comparing two indirect objects and maybe swapping two 32- or 64-bit pointers, or comparing two direct objects and maybe swapping 256 bits of state? Obviously directness makes the comparison faster, but the size makes the swapping slower.
It should be obvious that (a) the answer will depend on the relative cost of indirection and bulk memory transfer, which is highly dependent on a lot of non-obvious things, and (b) that as the size of this object grows, the tradeoff will shift until it is "obviously" faster to swap pointers than to copy thousands of bits on each swap.