【发布时间】:2015-03-02 11:08:07
【问题描述】:
到目前为止,在我正在编写的程序中,我一直在使用数组来存储有关线段的数据。为了这个问题,我们假设这些数组只包含定义 start (x1, y1) 和 end (x2, y2) 坐标的整数。
Integer[] lineData = {x1, y1, x2, y2};
在我的程序中,我需要使用 for 循环不断地对多个此类数组中包含的数据执行操作。
在编写程序的过程中,我多次意识到我需要更多关于这些段的数据。结果,我向数组中添加了元素,数组变大了,例如:
Integer[] lineData = {x1, y1, x2, y2, slope, red, green, blue, width};
这变得很难管理,因为我需要记住每个整数数据的位置才能对其执行操作,并且实现对数组的更改非常繁琐,例如交换两个元素的位置,因为我需要更新对它们执行操作的程序的每个部分中元素的索引。
这让我想到了创建一个包含整数作为其字段的 lineData 类的可能显而易见的想法:
public class LineData {
public int x1,y1,x2,y2,slope, red, green, blue, width;
LineData(int x1, int y1, int x2, int y2, int slope, int red, int green, int blue, int width){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.slope = slope;
this.red = red;
this.green = green;
this.blue = blue;
this.width = width;
}
public int getX1() {
return x1;
}
public void setX1(int x1) {
this.x1 = x1;
}
public int getY1() {
return y1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public int getX2() {
return x2;
}
public void setX2(int x2) {
this.x2 = x2;
}
public int getY2() {
return y2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public int getSlope() {
return slope;
}
public void setSlope(int slope) {
this.slope = slope;
}
public int getRed() {
return red;
}
public void setRed(int red) {
this.red = red;
}
public int getGreen() {
return green;
}
public void setGreen(int green) {
this.green = green;
}
public int getBlue() {
return blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
这看起来是一个很好的解决方案。
不过,我担心的是访问和更改 lineData 类的字段将比访问和更改数组中的元素慢。我担心的原因是相信数组的存在是有原因的。
使用 lineList 类的另一个参数是需要存储有关线段的数据,这些数据不是整数,而是字符串、布尔值和其他自定义对象。
但是,请忽略该论点。我想将整数数组与仅包含整数字段的类进行比较。
总结一下,我的问题是:
哪个更快:由 x 个整数组成的数组还是包含 x 个整数字段的对象? 当您过去遇到所描述的问题时,您是如何解决的?如果使用带字段的对象比使用数组慢,您是否仍然决定使用带字段的对象?为什么?
请考虑到这些数组的数量非常多,因此将数组更改为具有字段的对象会创建大量循环的实例化对象 - 也许这会影响性能?
非常感谢您的帮助!
【问题讨论】:
-
唯一确定的方法是对其进行基准测试。尽管存储效率可能不同,但总体上将有同样多的对象。另请注意,getter 和 setter 虽然经常被推荐,但不是强制性的。
-
对象更具可读性,我强烈建议您朝这个方向发展。
-
@DNA 你能告诉我我将如何进行基准测试或指出一些关于该主题的其他资源吗?
标签: java arrays performance class for-loop