【发布时间】:2013-11-25 13:12:50
【问题描述】:
我必须搜索对象列表以找到两个属性中较低的 2 个和较大的 2 个值。在 Java 中什么更有效:检查列表一次询问 4 个值还是检查两次以检查 2?以我的经验,1 循环应该更好,但可能存在我可能不知道的编译优化。
这是单循环的代码:
Cell[] getEdges(List<Cell> coordinateList)
{
int minX = coordinateList.get(0).getX;
int minY = coordinateList.get(0).getY;
int maxX = coordinateList.get(0).getX;
int maxY = coordinateList.get(0).getY;
Cell[] edgePair = new Cell[2];
For(Cell currentCell: List<Cell> coordinateList)
{
if(currentCell.getX()<minX)
{
minX = currentCell.getX();
}
if(currentCell.getY()<minY)
{
minY = currentCell.getY();
}
if(currentCell.getX()>maxX)
{
maxX = currentCell.getX();
}
if(currentCell.getY()>maxY)
{
maxY = currentCell.getY();
}
}
edgePair[0] = new Cell(minX, minY);
edgePair[1] = new Cell(maxX, maxY);
return edgePair;
}
这是 2 个循环的代码(最大值相同,只需更改条件)
Cell getMinEdge(List<Cell> coordinateList)
{
int minX = coordinateList.get(0).getX;
int minY = coordinateList.get(0).getY;
For(Cell currentCell: List<Cell> coordinateList)
{
if(currentCell.getX()<minX)
{
minX = currentCell.getX();
}
if(currentCell.getY()<minY)
{
minY = currentCell.getY();
}
}
return new Cell(minX, minY);
}
提前感谢您的任何建议。
【问题讨论】:
-
我想你是在比较六个和六个...
-
为什么要通过您的列表两次使您的代码更快?!
-
不要推测性能。通常:代码尽可能优雅和干净 - 然后它也会很快!如果速度不够快:使用分析器!其他都是猜测! (你知道投机给世界经济带来了什么......)
-
@Doorknob 这不是那么简单:在某些情况下循环两次可能会更快。例如,检查在交错时可能会争夺缓存。
-
建议:将所有出现的
if (a < min) { min = a; }替换为min = Math.min(a, min);,这样更易于阅读并且可能更快,并使用测试来确定您可以应用哪些其他改进来使您的代码更快。跨度>
标签: java for-loop performance