[Development] QVector reserve counterproductive?

Martins, Sérgio sergio.martins at kdab.com
Sun Mar 4 16:01:01 CET 2018


On 2018-03-04 13:20, Christian Ehrlicher wrote:
> Am 04.03.2018 um 10:03 schrieb Christian Ehrlicher:
>> Am 03.03.2018 um 23:22 schrieb Martins, Sérgio:
>>> On 2018-03-03 20:38, Christian Ehrlicher wrote:
>>> 
>>>> But it looks like reserve()
>>>> allocates *exactly* the amount of elements given.
>>> 
>>> Actually that qpainterpath code is off-by-one, it should be:
>>> d_func()->elements.reserve(d_func()->elements.size() + polygon.size() 
>>> - 1);
>>> 
>>> which also fixes the performance problem (by luck, in that specific 
>>> benchmark). Please test.
>> You're correct - this fixes the problem. Looks like the growth 
>> strategy is only applied when the current capacity == current size and 
>> not when the current capacity is slightly higher... good to know (and 
>> should maybe be documented?)
> The off-by-one idea was wrong. moveTo() will add another point to
> elements - therefore reserve(d_func()->elements.size() +
> polygon.size()) is correct.
> Maybe the best idea here would be to simply remove the reserve() calls
> and let QVector do what it is made for... :)

If you're sure you're not pessimizing any other case, then removing 
reserve() is fine.

But maybe there's a third option:

vec.reserve(qMax(needed, 
what_the_capacity_would_have_been_without_reserve))

this way it's good for short containers, as growth is bootstrapped and 
also good for big containers as reserving becomes a no-op, as there's 
already capacity.


Regards,
-- 
Sérgio Martins | sergio.martins at kdab.com | Senior Software Engineer
Klarälvdalens Datakonsult AB, a KDAB Group company
Tel: Sweden (HQ) +46-563-540090, USA +1-866-777-KDAB(5322)
KDAB - The Qt, C++ and OpenGL Experts



More information about the Development mailing list