qobject_cast

Olivier Goffart <[email protected]> Sat, 12 Nov 2005 11:18:28 +0100
Newsgroups gmane.comp.kde.devel.optimize
Message-ID <[email protected]>
Hello.

When browsing the kdelibs code, i seen sometimes in the code few qobject_cast 
when i would used dynamic_cast

So my question was, what's the difference between qobject_cast and 
dynamic_cast ?

After having doing some test, it seems that qobject_cast is 3 times faster 
than dynamic_cast.

So I'll change my habit, and use qobject_cast instead of dynamic_cast when 
casting objects.

Of course, I must continue to use static_cast which is still 10 times faster 
than qobject_cast when i know what my object is.


The attached test, compiled with -O2
no cast: 11 ms
static_cast: 19ms   ratio: 1.72727
dynamic_cast: 872ms   ratio: 79.2727
qobject_cast: 290ms   ratio: 26.3636   dynamic ratio :3.0069

note that when i compile with -O0 ,  static_cast is faster than no cast, 
strange.

_______________________________________________
Kde-optimize mailing list
[email protected]
https://mail.kde.org/mailman/listinfo/kde-optimize
test_cast.cpp (text/x-c++src, 1.1 KB)
#include "test_cast.h"

#include <QDateTime>

#include <iostream>

int main()
{
	QTime ti;
	int cu_ti;
	Test T;
	T.i=0;
	T.j=0;
	Test *t=&T;
	QObject *o=&T;

	ti.start();
	do
	{
		t->i++;
		t->j++;
	} while(t->i<8000000);
	int base=ti.elapsed();
	std::cout << "no cast: " << base << " ms\n";

	T.i=0;
	ti.start();
	do
	{
		static_cast<Test*>(o) ->i++;
		static_cast<Test*>(o) ->j++;
	} while(static_cast<Test*>(o)->i < 8000000);
	cu_ti=ti.elapsed();
	std::cout << "static_cast: " << cu_ti << "ms   ratio: " << (double)cu_ti/(double)base << "\n";
	
	T.i=0;
	ti.start();
	do
	{
		dynamic_cast<Test*>(o) ->i++;
		dynamic_cast<Test*>(o) ->j++;
	} while(dynamic_cast<Test*>(o)->i < 8000000);
	cu_ti=ti.elapsed();
	std::cout << "dynamic_cast: " << cu_ti << "ms   ratio: " << (double)cu_ti/(double)base << "\n";
	
	T.i=0;
	ti.start();
	do
	{
		qobject_cast<Test*>(o) ->i++;
		qobject_cast<Test*>(o) ->j++;
	} while(qobject_cast<Test*>(o)->i < 8000000);
	int qo_ti=ti.elapsed();
	std::cout << "qobject_cast: " << qo_ti << "ms   ratio: " << (double)qo_ti/(double)base << "   dynamic ratio :" << (double)cu_ti/(double)qo_ti  << "\n";
	
	return 1;
}


#include "test_cast.moc"
test_cast.h (text/x-c++hdr, 150 B)
#ifndef TTTTT
#define TTTTT

#include <QObject>
#include <QString>

class Test : public QObject
{ Q_OBJECT
public:
	int i;
	int j;
	int h;
};

#endif
signature.asc (application/pgp-signature, 189 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQBDdcF9z58lY8jWrL0RAuJ9AJ9gz9iBpP9bhcOB+TtaHHE644+dMACcCrz8
DDYT3gYlppeT9aB6hK/Sc88=
=RJpG
-----END PGP SIGNATURE-----