[Development] How qAsConst and qExchange lead to qNN

Ulf Hermann ulf.hermann at qt.io
Wed Nov 16 09:05:20 CET 2022

>> That's a deep copy. A deep copy of a string is obviously more expensive
>> than the overhead of calling the QString ctor and dtor.
> That remains to be proven. A rule of thumb for atomics is that they're
> two orders of magnitude slower than a normal int. They also still act as
> optimizer firewalls. With that rule of thumb, copying 50 char16_t's is
> faster than one ref-count update. What really is the deciding point is
> whether or not there's a memory allocation involved. I mentioned that
> for many use-cases, therefore, a non-CoW SBO container is preferable over a CoW
> non-SBO one.

As stated elsewhere, the real problem about the deep copy is the 
allocation involved in it, not necessarily the copying of the elements.

>> I can't say what case is more common. What I can say is that the risk of
>> creating deep copies sounds worse to me than the risk of calling the
>> QString ctor and dtor too often.
>> This is what I mean with "fuzzy". We don't really have the data to
>> support a move to QAnyStringView for all of our API.
> I can say with firm belief that, _atm_, passing QString is more common.
> But this is a self-fulfilling fact. The tst_qsettings experiment shows
> what can happen if you port an API that doesn't naturally receive
> pre-made QStrings.

Are we in a position to change how people use our APIs? I can say with 
firm belief that most existing applications using Qt will not be 
rewritten from the ground up to avoid passing QString and QList to Qt 
APIs. So they will pay the cost of deep copies if we force 
QAnyStringView and QSpan on them by changing our API. There are lots of 
existing Qt applications. Your CO2 calculation doesn't look that great then.

New APIs that are not used in the "wrong" way all over the world, yet, 
are a different story. If we can provide a clean QAnyStringView or QSpan 
override without ambiguities, it's also  a different story. (But adding 
complexity to the API is still a thing).

Maybe we can approach this in a module-by-module way. QtWidgets is 
probably pretty "bad" regarding QList and QString arguments, and no one 
will change their old widgets applications to suit our newfangled 

QtQml and QtQuick, on the other hand, hardly have any C++ API, and most 
QML and QtQuick applications are not that old. We might get away with 
changing API there.

QtCore and QtGui is where the most difficult decisions are to be taken, 
I guess.

best regards,

More information about the Development mailing list