momo momo - 3 months ago 11
Java Question

Java - weight of instantiation

Say I've got a very lightweight object:

public class Point {
public int x;
public int y;
public Point(int ax, int ay){
x = ax;
y = ay;
}
}


And I need to calculate distance very frequently - for example, during a scroll event on a mobile device that might fire several times per second.

If it keeps the code a little cleaner and more transparent to use new Point(a, b) each time, is the performance hit significant enough that I should consider caching a few references and update the member variables (as opposed to instantiation)?

Answer

Updating previous instance will not allocate new memory but creating new instance will. Time to time jvm garbage collector will free memory. You don't have control over that. So it's always better to update existing instance unless you are keeping the history.

However you can always use a setter function.

public class Point {
  public int x;
  public int y;
  public Point(int ax, int ay){
   this.setXY(ax, ay);
  }
  public void setXY(int ax, int ay){]
    x = ax;
    y = ay;
  }
}