efficiency vs. immutability of inline classes
Jona Christopher Sahnwaldt
jc at sahnwaldt.de
Fri Aug 21 15:02:14 UTC 2020
Hi,
In C, it's common to have arrays of structs. Because structs are mutable, I
can iterate through an array and update a single field in each struct.
To do something similar with Java inline classes, since they are immutable,
I'd have to make a modified copy of each array item and copy the result
back into the array. This might be much less efficient than the C approach.
First a general question: This has probably been discussed before (but I
didn't find it in the list archive). What's the current thinking? Could
someone point me to any discussions or results? Thanks!
More specific questions: I recently read about "functional transformation
of immutable objects".
https://github.com/openjdk/amber-docs/blob/master/eg-drafts/reconstruction-records-and-classes.md
This feature may initially be intended for records, but let's apply it to
inline classes:
InlineType[] a = ...; // InlineType has a field x
for (int i = 0; i < a.length; i++)
a[i] = a[i] with { x = 3; };
Semantically, this makes two copies (from array to local variable and back).
Could the JIT be smart enough to transform this into an update of a single
field, without any copies of the whole object?
Or maybe we should give the JIT a hint and allow compound assignment
analogous to += et al.?
a[i] = with { x = 3; };
or
a[i] with= { x = 3; };
OK, the syntax isn't pretty, but maybe it helps improve performance... ;)
Regards,
Christopher
More information about the valhalla-dev
mailing list