True pre-allocation of structure array?!

조회 수: 10 (최근 30일)
Johannes Pohl
Johannes Pohl 2018년 8월 17일
편집: James Tursa 2018년 8월 17일
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
James Tursa
James Tursa 2018년 8월 17일
편집: James Tursa 2018년 8월 17일
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.,

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2018년 8월 17일
편집: Stephen23 2018년 8월 17일
" 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:

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by