I am creating a java program which will have to deal with a LOT of Points. When I say a lot, I am talking about upwards of 100,000 Points. Furthermore, I will have to be creating points over and over again. I am worried that this object creation will slow down my algorithm time, and use up big chunks of memory.
I have come up with few possible solutions, would these work? Are there better ways to handle the situation?
Solution 1) -A Point "Factory", where all points are sent to instead of being destroyed. Here, they will be recycled so we do not have to re-create an object.
public class PointFactory {
public final static List<Point> unused = new ArrayList<Point>();
public static void disposePoint( Point point ){
unused.add( point );
}
public static void disposePoints( List<Point> points ){
for( Point point: points )
unused.add( point );
}
public static Point newPoint( int x, int y ){
if( unused.isEmpty() )
return new Point( x, y );
else{
Point point = unused.get(0);
point.x = x;
point.y = y;
return point;
}
}
}
Solution 2) Very similar to solution 1, but uses a new structure "XY", to avoid un needed overhead. All I need are X and Y values.
public class XYFactory {
public final static List<XY> unused = new ArrayList<XY>();
public static void disposeXY( XY xy ){
unused.add( xy );
}
public static XY newXY( int x, int y ){
if( unused.isEmpty() )
return new XY( x, y );
else{
XY xy = unused.get(0);
xy.x = x;
xy.y = y;
return xy;
}
}
}
public class XY {
public XY( int x, int y ){
this.x = x;
this.y = y;
}
public int x;
public int y;
public boolean equals( Object o ){
if( !( o instanceof XY ) )
return false;
XY xy = (XY)o;
return xy.x == x && xy.y == y;
}
}