Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java ready for a HashCode record?

Records represent immutable state and are candidates for stack inlining.

If I declare a draft outline of a HashCode record, similar to a message digest class, like so:

public record HashCode(int value) {
    HashCode update(int value) {
        return new HashCode(value() * 31 + value);
    }
    // ... other update convenience methods here
}

Will the JIT immediately unroll HashCode instances onto the stack for the following approach to hashCode generation?

HashCode hashCode = new HashCode(0);
for (Object field : fields) {
    hashCode = hashCode.update(field.hashCode());
}
hash = hashCode.value();

Or will I encounter pitfalls like unnecessary object churn?

This record definition seems like a silver bullet approach to efficient inline hashCode generation.

Are there any downsides to this approach?

I recognise that hashCode generation can be influenced by prior knowledge of the distribution of the data being hashed, but this record seems like a drop in replacement for the multiply and add code that's repeated everywhere, and could even be accommodating to any kind of update, for example other methods could update via xoring etc.

I'm going to try the above HashCode record but I only like to embrace higher level idioms if I fully understand the tradeoffs I'm making between usability and performance.

like image 882
gary Avatar asked Nov 03 '25 06:11

gary


1 Answers

I think I found my answer in another stackoverflow post: Are Java records stack allocated like C# structs? There are upcoming proposals for Value types, which will achieve this via Scalarization:

In C2, value objects on the stack are typically scalarized when stored or passed with concrete value class types. Scalarization effectively encodes each field as a separate variable, with an additional variable encoding null; no heap allocation is needed.

and

Record classes will be able to be declared as value or primitive types to support this sort of stack allocation, but are not required to be.

So record types are not the intended solution to this.

like image 140
gary Avatar answered Nov 04 '25 20:11

gary