我试图获得两个矩形的交点。我有一个方法,但是当我用40000矩形的算法测试它时,我得到一个OutOfMemory错误。我检查交叉点的次数完全是O(n²),但所花费的时间不是。 我认为内存不足是因为有太多的对象,但它所需要的时间不是O(n²)(用双倍测试测试)对我来说没有意义,我不明白为什么它是这样做的。获取矩形的交点不是O(n²)和OutOfMemory
这是我得到的交集
public void getIntersections(Rectangle r, Collection<double[]> c) {
x1 = Math.max(this.getLowerLeftX(), r.getLowerLeftX());
y1 = Math.max(this.getLowerLeftY(), r.getLowerLeftY());
x2 = Math.min(this.getUpperRightX(), r.getUpperRightX());
y2 = Math.min(this.getUpperRightY(), r.getUpperRightY());
if(this.contains(x1,y1) && r.contains(x1,y1)) {
inter[0] = x1;
inter[1] = y1;
c.add(inter.clone());
}
if(this.contains(x1,y2) && r.contains(x1,y2)){
inter[0] = x1;
inter[1] = y2;
c.add(inter.clone());
}
if(this.contains(x2,y1) && r.contains(x2,y1)){
inter[0] = x2;
inter[1] = y1;
c.add(inter.clone());
}
if(this.contains(x2,y2) && r.contains(x2,y2)){
inter[0] = x2;
inter[1] = y2;
c.add(inter.clone());
}
}
我试图使这是内存和CPU高效的代码,但它仍然无法正常工作,因为它应该。 任何帮助,不胜感激。
编辑: 调用该函数的算法:
public void execute() {
List<Rectangle> rectangles = this.getRectangles();
Queue<Rectangle> q = new LinkedList<Rectangle>();
q.addAll(rectangles);
System.out.println(q.size());
while(!q.isEmpty()){
Rectangle check_rect = q.poll();
for (Rectangle rect: q) {
check_rect.getIntersections(rect, this.getIntersections());
}
}
}
辅助功能:
public boolean contains(double x, double y){
return ((x == this.getLowerLeftX() || x == this.getUpperRightX()) ||
(y == this.getLowerLeftY() || y == this.getUpperRightY())) &&
x >= this.getLowerLeftX() && x <= this.getUpperRightX() &&
y >= this.getLowerLeftY() && y <= this.getUpperRightY();
}
对于交叉口的集合,我使用:
this.intersections = new ArrayDeque<>();
的OutOfMemory例外总是当它试图放大ArrayDeque时发生>(),它只将交点存储在double [2]中。所以看起来40000个矩形之间的交叉点太多了。 另一个问题似乎是内存耗尽之前的迭代,它真的放慢速度,这是因为交换或其他内存管理?
你看过性能下降的动态(1000,5000,10000矩形)吗?你也应该提供调用这个方法的代码,因为问题可能在那里。你的方法也适用于副作用,这被认为是不好的做法。通常你想返回一个新的交集对象,而不是操纵输入和全局变量。 – user3707125
你能否提供这里使用的所有方法的实现?这意味着所有的'getLowerRight','getUpperLeft'等方法和'contains'方法。另外请包括'inter'数组的声明 –
我添加了更多信息,以便您可以看到我在做什么。 – Midasso