Yes, what is somewhat sucky about it is that it allocates the space twice, initializes one copy then copies it (then frees one); though I haven't checked this assumption of mine. Which means iterating over the requested size twice. Pre-sizing avoids reallocating. Reallocating is done exponentially (doubling the size each time) and so averages out to copying the maximum size about twice (unless you get lucky and reallocate in-place, rather unlikely in my experience). So it isn't surprising that the performance difference is minimal between those two choices.
But note that pre-allocating will likely reduce a bit of memory fragmentation by avoiding leaving those power-of-two-sized buffers of now-free space in its wake.
- tye
In reply to Re^3: Pre-grow a string (speed)
by tye
in thread Pre-grow a string
by diotalevi
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |