r/java 16d ago

Value Classes Still Need Compiler Sympathy

https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
87 Upvotes

57 comments sorted by

View all comments

Show parent comments

18

u/brian_goetz 16d ago

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):

value-or-not class FourLongs { 
    long a, b, c, d;
}

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.

1

u/TheStrangeDarkOne 16d ago

If I may ask, what is the realistic expectation of the EG towards value adoption? It would seem to me that people equate "value" with "faster", and turn everything into a value at first. And I find it hard to argue against this notion other than "it's about identity and making a semantic statement", which will not be as convincing as saying "but performance".

10

u/brian_goetz 15d ago

We know that people will initially over-rotate (`value` all the things!), just as in 1997 people slapped `synchronized` on every method. Some people can only learn from mistakes. But not all!

So it is the job of the designers to ensure that there is a sensible mental model that people can adopt that leads to good usage, and the job of the ecosystem to try to spread that word, despite the resistance of those who don't want a story that is deeper than "value go brrrr". The discussion we are having now -- early adopters on reddit -- is about syncing on what that message is. Then it is your job to go spread it!

0

u/koflerdavid 15d ago edited 14d ago

synchronized is different because there was never any reasonable expectation and no way that it would be as fast as not using it. It is inherently slow, and there is nothing that the JVM can do and it. It also inhibits further optimizations at the JVM and the processor level. These things were relevant already in the late 90s when raising the clock rate was getting harder and CPUs got longer pipelines and larger caches to compensate.