cocos2d-x icon indicating copy to clipboard operation
cocos2d-x copied to clipboard

RichText._fontElements Why is the initialization size 20 instead of 0?

Open tidys opened this issue 2 years ago • 4 comments

https://github.com/cocos2d/cocos2d-x/blob/cd7446f17956d73041f9b33b37b4c747c6bc1993/cocos/ui/UIRichText.cpp#L361

I see that properties are looked up in reverse order when they are fetched, and default values are returned when they are not found change pr: https://github.com/cocos2d/cocos2d-x/commit/a8ddbdc12c233c52b2746cd03e806d0fc59c2cdb

tidys avatar Jul 06 '22 07:07 tidys

I think it's just an educated assumption that anyone using the UIRichText widget/class will on average have at least 20 different attributed text nodes in its content. I believe that this trades off a zero-initialized allocation at construction instead of resizing the std::vector a few times if it starts empty.

stevetranby avatar Jul 13 '22 04:07 stevetranby

At the beginning I also thought it was pre-allocating some space, but then I saw that it was push and pop operations on top of 20, and if everything was normal, the first 20 elements of the array were not accessible

tidys avatar Jul 13 '22 05:07 tidys

Ah, yeah it's very likely you're correct on that, but regardless it does makes sense to just initialize it to zero (0) because the UIRichText widget and associated MyXMLVisitor are used where performance is not critical.

And, to be honest, I'd be a bit surprised if UIRichText is used in many games.

Feel free to edit in github as a PR for the actual team to change this.


note: based on your comments, and taking a quick glance over the entire UIRichText.cpp source in github, I'm guessing the reason this is benign is that initializing 20 unused attributes probably does eliminate one or two resize growing allocations and each of these 20 default initialized UIRichText::Attributes instances have default values which then cause the each of the MyXMLVisitor::getXXXX functions to return a literal "default" value (ie: 12 in getFontSize). Therefore it's not an issue to set it as _fontElement(20), but it does make sense to change it back to 0 (or remove it to allow default init).

stevetranby avatar Jul 13 '22 06:07 stevetranby

It is likely that this is the author of a handwritten 20, I tried to modify to 0, temporarily did not find any problems

tidys avatar Jul 14 '22 02:07 tidys

Don't waste time on this project

qx avatar Aug 28 '22 10:08 qx