On Thursday, January 21, 2016 12:10:21 PM CET Matthew Woehlke wrote: > On 2016-01-20 23:44, Kevin Kofler wrote: > > Almost all my containers grow with allocations. How should I know in > > advance how much memory to reserve? It'd just waste an arbitrary amount > > of memory and then still end up reallocating because it'll inevitably be > > exceeded at some point. Variable-size containers are variable-size for a > > reason. > > > > I consider reserve() to be a technical detail and a micro-optimization I > > really should not have to bother with in 99+% of the cases. > > 99% is almost certainly an exaggeration. > > There are three categories of containers: > - size is constant and known at compile time > - size is constant and known at run time > - size is variable (e.g. based on user actions) > > There are quite a few instances of the second category. For example, in > reading a PLY file, the number of points and faces is (usually) known as > soon as the header is read. Obviously, these depend on what file is > being read, so the size is not a *compile* time constant, but it is > known prior to filling the container, and is for the most part constant. > Cases like these (or filling one container based on the contents of > another) are where reserve() is extremely helpful, and most certainly > more than "a technical detail and micro-optimization". > > That's not to say that there aren't *also* instances of the third. > > (And, yes, pedantically, in reality it is more like a continuum than > three distinct categories.)
And even in the third case one can usually do an educated guess as to the expected size and use that for reserve optimizations. Inside Qt itself, I've done so most recently for moc and saw significant speedups. How you do that? Dump the final size of the container and do statistics to calculate the mean or average and use that. Then compare the performance (including memory consumption) before/after and see if it's worth it. As always, you need to actually measure instead of going by rule of thumb or hand wavy arguments. -- Milian Wolff | milian.wo...@kdab.com | Software Engineer KDAB (Deutschland) GmbH&Co KG, a KDAB Group company Tel: +49-30-521325470 KDAB - The Qt Experts
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________ Development mailing list Development@qt-project.org http://lists.qt-project.org/mailman/listinfo/development