[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-core-devel
Subject:    inefficient QString coding practice
From:       "Dr. Juergen Pfennig" <info () j-pfennig ! de>
Date:       2004-03-13 13:02:39
Message-ID: 200403131402.39212.info () j-pfennig ! de
[Download RAW message or body]

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

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic