From kde-core-devel Sat Mar 13 13:02:39 2004 From: "Dr. Juergen Pfennig" Date: Sat, 13 Mar 2004 13:02:39 +0000 To: kde-core-devel Subject: inefficient QString coding practice Message-Id: <200403131402.39212.info () j-pfennig ! de> X-MARC-Message: https://marc.info/?l=kde-core-devel&m=107918297601628 Hello Coders, when browsing through kdelib I find that most programmers rely on the fact the QT handles implicit conversions of "const char*" (or C-String literals) to QString correctly and efficient. QT does usually a good job, they have a lot of QString member functions that take "const char*" overloads. But often I find code fragments like: if (extension == QString::fromLatin1(".wav")) .... The programmer probably wanted to avoid the implicit creation of a QString (which isn't the case, see below). But the result is a little desaster! In his code a temporary QString gets created (and destroyed). This QString causes 2 mallocs (and 2 frees). The compiler generates maybe 30 bytes for an Xtor, the compare and a Dtor. If we look into QT's source code, we find that QT would handle if( extension == ".wav") ... much more efficient, because it has an overloaded == operator for "const char*". Here is the source from qstring.cpp: bool operator==( const QString &s1, const char *s2 ) { if ( !s2 ) return s1.isNull(); int len = s1.length(); const QChar *uc = s1.unicode(); while ( len ) { if ( !(*s2) || uc->unicode() != (uchar) *s2 ) return FALSE; ++uc; ++s2; --len; } return !*s2; } Great - no malloc/free needed and the compiler will only need around 10 bytes for a simple call to operator==. Conclusion: let QT do the job - and change code like the example above to keep KDE small and fast. Jürgen