PDA

View Full Version : Can QHash::capacity() be smaller than QHash::size()?!?



iw2nhl
24th August 2007, 00:44
I'm trying to optimize memory usage in my code.
I found that some Qt containers have capacity(), reserve() and squeeze() functions for this purpose.
Making some tests I found a strange result (among normal ones!):
in some conditions I get capacity() < size().
If I understand correctly the documentation, capacity() should give the number of allocated items (which generally is greater than the number of inserted items, for speed reasons).



QHash< DataUniqueId, DrawItem* > m_lookupTable;

// Insert data into m_lookupTable
for (...) {
m_lookupTable.insert(..., ...);
}

qDebug() << m_lookupTable.size() << m_lookupTable.capacity();

// No more insertions, so release any unused memory
m_lookupTable.squeeze();

qDebug() << m_lookupTable.size() << m_lookupTable.capacity();


This is the output:


500 521
500 257


As you can see, after the squeeze(), size() > capacity().
How can the number of allocated items be less than the number of real items?
Am I doing something wrong?

Thanks in advance,
Alessandro

jacek
24th August 2007, 02:00
If I understand correctly the documentation, capacity() should give the number of allocated items (which generally is greater than the number of inserted items, for speed reasons).
In case of QHash the docs say:
int QHash::capacity () const
Returns the number of buckets in the QHash's internal hash table.
Buckets are not items --- they might contain more than one (key, value) pair.

iw2nhl
24th August 2007, 02:17
Buckets are not items --- they might contain more than one (key, value) pair.

Thank you very much for the explanation!
Now I'm more secure about my code...