I tried to debug both methods Array::ensureStorageAllocated() and Array::resize().
But actually it is too complicated for me, that’s why I would kindly ask if anyone could explain me what is actual difference?
As I understand ensureStorageAllocated() is useful when we want to avoid reallocating memory each time Array::add() is called. Because ensureStorageAllocated() reallocates all memory at once. But as I understand resize() does that at once also. Doesn’t it?
To be honest my main issue is preallocating memory for juce::Path. I see that Path has method preallocateSpace() and inside it there is used Array::ensureStorageAllocated(). But I am not sure if I use it in appropriate way which is:
I prepare and paint new Path in each callback of VBlankAttachment. What is worth to notice my Path in each callback has always the same num of points (to be more precise by point I mean startNewSubpath() followed by lineTo()).
In each callbeck before creating new Path I call Path::clear(). Due to fact Path::clear() does not rellocating memory (there is used Array::clearQuick()) I use Path::preallocateSpace(4*numOfPoints + 8) only once in my Component::resized().
Is it appropraite implementation? Or should I call instead Path::preallocateSpace(4*numOfPoints + 8) in each VBlankAttachment callback?
Maybe it looks like the subject is not clearly related with Array::ensureStorageAllocated() but I just try to understand all those things.
Like a std::vector, juce::Array internally has a capacity (total number of allocated elements) and a size (number of elements in use), where the size is always smaller or equal to the capacity.
Yes, if you call ensureStorageAllocated (N) or resize (N), you’ll always have a capacity of at least N after the call. However, ensureStorageAllocated won’t affect the current size, whereas resize will set the current size to N.
Assuming you’re reusing the same Path instance on each vblank callback, and that numOfPoints is constant, then you would only need to call this function once to reserve the required capacity.
But just to be perfectly sure.
Let’s say for some reason I would create my own MyPath class (or something similar) and in MyPath I would provide two methods:
MyPath::preallocateSpace() - which would use internally (as it is in Juce) Array::ensureStorageAllocated()
MyPath::resizeSpace() - which would use internally Array::resize()
Then would it make a difference in my case if I call MyPath::preallocateSpace(4*numOfPoints+8)
or MyPath::resizeSpace(4*numOfPoints+8)
In terms of allocations, it wouldn’t matter. You’d allocate the same amount of memory in each case.
The difference would be if you ever ended up using fewer than the expected number of points. If you called resize(N), the path would have a size of N, so you’d need to make sure that all N points were valid. If you called preallocateSpace(N) instead, then you could more gracefully handle the situation where the path used fewer than N points.