Does Java optimise this...


public Point getLocation()
{
     return new Point(this.x, this.y);
}

I’ve read, from a random site, that Java optimises this piece of code to use the same object but with different values, so you will not be creating objects all the time.

Basically Java’s optimisation does is have a pointer to the Point object and just replaces the appropriate x and y values.
Is this true or have I been reading way too much crap?

I have no idea if it’s optimised out, but I personally prefer an ImmutablePoint interface with getX/Y methods. Then your Point can implement that and you just have to return the point. Kinda a workaround for not having a proper C++ style ‘const’.

Hmmm… What if you do this:


for (int i = 0; i < 10000; i++) {
  this.x = this.y = i;
  point[i] = getLocation();
}

This would surely create new Point objects, right?

Anyway, there’s 2 reasons why I think you shouldn’t depend on an optimization like this:

  1. Java doesn’t optimize this, maybe a specific JVM does.
    You don’t want to depend too much on VM specific optimizations.

  2. It doesn’t make any sense to create new Point objects for getting the location of some object everytime you query it. Point has getters and setters anyway.

EDIT: 3) What Orangy Tang said ;D

Recently I’ve been doing a lot of reading about VM optimisations, Sun doesn’t mention everything the VM optimises.

I wish they would.

Swing API is full of “duplicate” methods like getPoint() / getPoint(Point p)

Meaning if you have already a mutable point, and you know you can share it across method calls, just pass it as reference and there won’t be any object allocation, and if you haven’t got one, a new instance will be created…

Lilian

I tend to use not duplicate methods, but pass-return types like:


public Vector3f getWhatever(Vector3f dest, ...) {
  if (dest == null) {
    dest = new Vector3f;
  }
  ...
  return dest;
}

What’s wrong with Overloading?