0

Suppose I already have a class Vector:

class Vector {
    public final double x;
    public final double y;
    
    public Vector(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double distance(Vector other) {
        return Math.sqrt(x * other.x + y * other.y);
    }
}

And now a new method is implemented with the help of the existing one:

double distance(double x1, double y1, double x2, double y2) {
    Vector v1 = new Vector(x1, y1);
    Vector v2 = new Vector(x2, y2);
    return v1.distance(v2);
}

v1 and v2 are created by new operator, so they are allocated on the heap. After this method returns, the two objects are no longer referenced and will be collected sometime later by gc.

But in fact that is redundant. Both v1 and v2 are created locally; they are not returned outside; they are not assigned to other objects;

v1 was not passed to other methods, so there can't be any assignment anywhere. v2 was passed to v1.distance, which is also "simple" (no assignment, if we check it).

So we can conclude that, both v1 and v2 are "local" and it's safe to release the resources just on the method returns. So there's no need to make gc busier at all.

My question is, will java do some optimization like that ? Or will JIT do something like that ?

Nathan Hardy
  • 156
  • 6

0 Answers0