gpt4 book ai didi

java - 防止对象创建的合适方法?

转载 作者:行者123 更新时间:2023-11-29 10:18:19 25 4
gpt4 key购买 nike

我正在创建一个 java 程序,它必须处理很多点。当我说很多时,我说的是 100,000 点以上。此外,我将不得不一遍又一遍地创造点数。我担心这个对象创建会减慢我的算法时间,并耗尽大块内存。

我想出了几个可能的解决方案,这些可行吗?有没有更好的方法来处理这种情况?

解决方案 1) -A点“工厂”,所有点都被发送到这里而不是被销毁。在这里,它们将被回收,因此我们不必重新创建对象。

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;

}

}

解决方案 2) 与解决方案 1 非常相似,但使用新结构“XY”以避免不必要的开销。我只需要 X 和 Y 值。

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;

}

最佳答案

如果仅使用两个整数构建一个对象所花费的时间对您的应用程序造成了损失,我会感到惊讶。我敢打赌,维护对象池或工厂的开销会产生类似的开销,但这需要进行概要分析。但是,如果您发现这是一个问题,请考虑构建一个 Object Pool

关于java - 防止对象创建的合适方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12063800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com