I am trying to convert a Qt object into a C++ class object in a loop like this
std::vector<PBWMPlugDeviceGraphicsItem*> deviceItms;
for(int i=0; i<fScene->items().size(); i++)
deviceItms.push_back(dynamic_cast<PBWMPlugDeviceGraphicsItem*>(fScene->items().at(i)));
Where PBWMPlugDeviceGraphicsItem
is a C++ class. It seems that, when total no. of items is larger than a certain threshold (e.g. fScene->items().size() >900
), it takes a considerable amount of time to convert these objects and because of that I can see operation on my QGraphicsScene
to be very slow. I read that dynamic_cast
has serious performace issues.
Is there any other great/fast way to achieve the same result?
Thanks!
The problem is calling
QList::at
, which returns reference to list item, which causesQList
to do copy-on-write detach.Minimal solution is to call
QList::value
to get the pointer, instead ofat
.Other solution is to fetch the list once, as explained in other answers. This way detach will only happen once even if you use
at
.You could also force use of const version of
at
by cast or temp variable.