我正在分析我的游戏,看来我在这里花了很多时间:
const Rectangle Widget::getAbsoluteRectangle() const
0.01s {
Point absLocation;
0.00s absLocation = getLocation();
if(!getParent())
{
return Rectangle(absLocation.getX(),absLocation.getY(),
getSize().getWidth(),getSize().getHeight());
}
const Widget* parent = this;
int eX = 0;
int eY = 0;
while(parent->getParent() != NULL)
{
0.02s parent = parent->getParent();
0.01s eX = parent->getMargin(SIDE_LEFT);
0.04s eY = parent->getMargin(SIDE_TOP);
0.03s absLocation.setX(absLocation.getX() + parent->getLocation().getX() + eX);
0.04s absLocation.setY(absLocation.getY() + parent->getLocation().getY() + eY);
}
0.02s return Rectangle(absLocation,getSize());
0.01s }
我想也许缓存这个结果并在其 parent 之一移动或调整大小时使其无效但首先我想知道是否有任何明显的优化。
谢谢
最佳答案
你的问题是你每次都在重新计算 parent 的位置。你需要做的是一个递归算法来一次计算它们。例如:
class Widget {
public:
Rectangle AbsolutePosition;
Rectangle RelativePosition;
std::vector<Widget*> children;
void ComputePositions(Rectangle ParentPosition) {
ComputeAbsoluteFromParentAndRelative(ParentPosition);
std::for_each(children.begin(), children.end(), [&](Widget* child) {
child->ComputePositions(AbsolutePosition);
});
}
};
使用此方法,每个小部件的位置仅计算一次且恰好一次,并且当前的绝对位置已被缓存。此外,如果需要,循环可以简单地并行化,因为每次迭代都是独立的。最后,您可以轻松控制调用 ComputePositions
的级别,而不必每次都在根目录调用它。
关于c++ - 优化获取 Widget 的绝对矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10054257/