[Qt-interest] Is Qt smart anough not to load the same icon resource multiple times?
Girish Ramakrishnan
girish at forwardbias.in
Fri Feb 18 19:09:11 CET 2011
Hi
On Fri, Feb 18, 2011 at 9:48 PM, Stephen Kelly <steveire at gmail.com> wrote:
> Girish Ramakrishnan wrote:
>
>> Hi Daniel,
>>
>> On Thu, Feb 17, 2011 at 3:36 PM, Daniel Price <daniel.price at fxhome.com>
>> wrote:
>>> If I create multiple instances of a custom widget that loads an icon from
>>> a resource like this:
>>>
>>>
>>>
>>> m_icon(QPixmap(“:/MyIcons/MyIcon.png”))
>>>
>>>
>>>
>>> is Qt smart enough to load the icon only once and implicitly share the
>>> resource? Or it is loading the same icon multiple times and wasting
>>> memory?
>>>
>>>
>>
>> Yes. In addition to implicit sharing, QImage/QPixmap have a mechanism
>> to share the data if they are from the same source. See
>> QPixmap/QImage::cacheKey.
>>
>> This means that even with implicit sharing is not in use,
>> QPixmap p1("foo.png");
>> QPixmap p2("foo.png");
>
> What about
> {
> QPixmap p1("foo.png");
> }
> {
> QPixmap p2("foo.png");
> }
>
> ?
>
> Does the cache key get invalidated on dtor?
>
My previous response was not correct. Let me try again :)
Only QPixmap has a mechanism to not load the the same file twice.
QImage does not have this mechanism. The only way for QImage to avoid
loading twice is by using implicit sharing (so the app has to maintain
our own QImage cache).
As for QPixmap, it just saves uses QPixmapCache internally to locate
the file again. In other words,
QPixmap p1("foo.png"); // saves it in QPixmapCache
...
QPixmap p2("foo.png"); // tries to get it from the QPixmapCache
Since I mentioned cacheKey in my previous mail, let me clarify that it
has nothing do with the internal caching. A new cacheKey is generated
for over new pixmap. One use of the QPixmap's cacheKey is that it can
be used as a non-reliable mechanism to compare pixmaps. For example,
p1.cacheKey == p2.cacheKey if p2 was found through the pixmap cache.
If cache keys differ, two pixmaps may still have the same contents.
Girish
More information about the Qt-interest-old
mailing list