Roll our own qUtf8Printable()?

Berthold Stoeger bstoeger at mail.tuwien.ac.at
Sun Feb 25 14:34:28 PST 2018


Hi,

On Sonntag, 25. Februar 2018 22:40:00 CET Lubomir I. Ivanov wrote:
> On 25 February 2018 at 21:39, Berthold Stoeger
> 
> <bstoeger at mail.tuwien.ac.at> wrote:
> > Dear all,

> > Much to my surprise, qUtf8Printable() produced larger code. The reason is
> > that it is defined as a macro in <qglobal.h>:
> > 
> > #ifndef qUtf8Printable
> > #  define qUtf8Printable(string) QString(string).toUtf8().constData()
> > #endif
> > 
> > It generates a temporary copy of the string! This looks like a defect to
> > me.
> the compiler could be missing an optimization opportunity for the copy?
> maybe the inline version (118 bytes) produces simply better optimized code.
> have your tried with a different compiler and playing with -Oxx?

This was with g++, -O2. -O3 gives exactly the same result.
With clang -O2 I get:

const char *test(const QString &s) { return qUtf8Printable(s); } -> 212 bytes
const char *test(const QString &s) { return s.toUtf8().data(); } -> 189 bytes
const char *test(const QString &s) { return qstring2c(s); }      -> 87 bytes

So an even higher relative gain (54%).

I think the compiler can't optimize the copy away, because QString doesn't 
copy the string, but does reference counting. I'm not sure if it is allowed to 
throw away the side effects of the ref()/deref() calls? This does some atomic 
stuff, so is obviously a bit hairy.

[Sidenote: There's a reason the C++-standard disallows reference counting for 
its string class.]

> my rule of thumb would be that we should reinvent the wheel for the
> sake of size or speed even.
> 1000 instances of the qUtf8Printable() macro would be 267 * 1000 and
> that's 267kb which isn't that much.

Worse, you'd only gain 118 bytes per invocation on g++. So not a huge gain, 
indeed. But better than nothing. The alternative would be replacing
  s.toUtf8().data()
by
  s.toUtf8().constData()
which seems more logical anyway. But it is quite unwieldy, so we might just as 
well hide it in a function, since Qt's implementation is broken.


Berthold


More information about the subsurface mailing list