Why doesn't Project Valhalla introduce mutable structs?

277 views Asked by At

Looks to me like primitive classes could behave more efficiently (at reasonable sizes) if they weren't immutable as currently proposed, but worked more like C structs.

Given this primitive class

primitive class Point implements Shape {
    public long x;
    public long y;

    public Point(long x, long y) {
        this.x = x;
        this.y = y;
    }

    public boolean contains(Point p) {
        return equals(p);
    }
}

interface Shape {
    boolean contains(Point p);
}

And an array Point[] points = new Point[N];

Why wouldn't we be able to do this?

points[0].x = 42;      //lastore
points[1].x++;         //laload, iinc, lastore

Point p = points[2];   //laload, laload
Shape s = p;           //new Point.ref (boxing)
p.x++;                 //iinc
assert !s.contains(p);

Instead it sounds like current design intends for the whole Point be read, mutated using withfield and written back in its entirety, which seems kind of wasteful - especially for larger types. Or would compilers routinely apply copy elision here?

Note that Point must be flattened instead of flattenable here, so the user can be certain not to mutate a shared instance.

Could someone further clarify the rationale behind immutability of primitive types?

@see

0

There are 0 answers