True pre-allocation of structure array?!
9 views (last 30 days)
Show older comments
Hey there.
I am capturing a video of a plot history in R2015a right now. This works quite fine. In the script, I am recording frames inside a for loop using the getframe() function. As there are lots of frames to be obtained, I am trying to pre-allocate the array for the frames using repmat():
F = repmat( getframe( hFig_cp ), 1, n_fr );
for fr = 1 : n_fr
F(fr) = getframe( hFig_cp );
end
This works. However, MATLAB does not truly allocate the memory for all the frames, but only references all array elements to the single, shared copy, and thus, still has to allocate new memory within every loop iteration. Questions: Would there still be a benefit in truly pre-allocating the array memory - or would MATLAB, just as it does inside the loop, even during pre-allocation just try to allocate single memory blocks for each array element alone? If yes, is there any possibility to avoid the shared copy referencing behavior?
Thanks!
1 Comment
James Tursa
on 17 Aug 2018
Edited: James Tursa
on 17 Aug 2018
The allocation that might make sense in your case would be to pre-allocate a 1 x n_fr struct with the known fieldnames of the getframe result (e.g., cdata and colormap), but with all of the initial elements unassigned (i.e. NULL in the background). That way F doesn't grow incrementally in the loop but at the same time there are no unnecessary elements pre-allocated. E.g.,
Answers (1)
Stephen23
on 17 Aug 2018
Edited: Stephen23
on 17 Aug 2018
" MATLAB does not truly allocate the memory for all the frames,"
And nor should it!
"Would there still be a benefit in truly pre-allocating the array memory "
It depends on what you are doing. For the code shown in your question it would not help to preallocate the contents of the structure because you totally reallocate the fields with new arrays within the loop, so any "preallocated" arrays just get discarded. Basically if you are doing this:
S(idx).field = new array
inside the loop then there is no advantage in trying to preallocate the fields: in fact it will just slow your code down because you pointlessly create some arrays in memory that don't get used and just get discarded within the loop.
However if you are using indexing into the field then preallocation can be useful:
S(idx).field(idy) = new elements
in exactly the same ways that any array should be preallocated rather than being enlarged in a loop.
This has been discussed before. As Loren wrote: "The key however is to try to not grow either the struct itself or any of its contents incrementally." See also:
0 Comments
See Also
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!