PDA

View Full Version : What is more efficient (qobject_cast or metaObject()->className())?



qt_developer
9th October 2013, 15:32
Hi all,

I have two versions of a code to detect if myWidget is a QCheckBox:



QCheckBox* checkBox = qobject_cast<QCheckBox*>(myWidget);
if (checkBox)
{
// do something
}




if ("QCheckBox" == QString(myWidget->metaObject()->className()))
{
// do something
}



What version is more efficient?

Best regards.

panithadrum
10th October 2013, 07:42
The best way is to benchmark it :P

The common way is the first, for a number of reasons:
- String compare is a slow task.
- You can easily fail when writing "QCheckBox" as a string. If you do, compiler won't tell you. If you mistype QCheckBox as a type inside qobject_cast, the compiler will complain.
- Using qobject_cast, you can access to specific members of QCheckBox if you need later on.

wysota
10th October 2013, 07:53
The difference in performance is so small, it is not worth considering. qobject_cast seems to be the more "proper" approach though in general.

Having said that I'll also add that if "do something" doesn't require anything from QCheckBox API then the whole if block is wrong and should be replaced with some virtual function call.