当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Optimizing getting absolute rectangle of Widget?

问题描述:

I'm profiling my game and it seems I spend a good amount of time here:

 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 }

I thought of maybe caching the result of this and invalidating it when one of its parents move or resize but first I'd like to know if there are any obvious optimizations.

Thanks

网友答案:

Your problem is that you're re-computing the parent's position every time. What you need to do is a recursive algorithm to compute them all at once. For example:

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);
        });
    }
};

Using this method, each widget has it's position computed only and exactly once, and the current absolute location is already cached. In addition, the loop can be parallelized if necessary trivially, since each iteration is independent. Finally, you can control easily the level at which ComputePositions is called, instead of having to call it at the root every time.

分享给朋友:
您可能感兴趣的文章:
随机阅读: