in reply to Re: How to implement a Queue that doesn't leak memory?
in thread How to implement a Queue that doesn't leak memory?
> it simply mentions reallocation and not leakage
yes, but the question could be if memory is released again.
IIRC, Perl's arrays are "improved" C-Arrays to have O(1) lookup.¹
The slots of the C-array are equally sized pointers to scalars holding the various data types
Furthermore will they always allocate a power of 2 of RAM, and only double if needed.
The empty slots are available as fill-in margins at the beginning and end of the C-array, The Perl is keeping a counters to see where the actual values start and end.
Like this unshift and push are O(1) if there is margin left. Otherwise reallocating more space only happens for doubling it. I.e. complexity is negligible since it only happens in O(log) occasions.
This bargaining of time-complexity for space-complexity allows nearly as efficient appending operations like linked lists have.
Now in theory it could happen that you have an array of a handful elements and after 1 million combined push and shift operations it allocates megabytes of space while not logically growing.
I doubt this happens and otherwise should be easy to demonstrate by the OP with a loop and using Devel::Size before and after.
1) see also https://blob.perl.org/tpc/1998/Perl_Language_and_Modules/Perl%20Illustrated/#AV
It could also be an issue if the OS doesn't "take back" released memory.
Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: How to implement a Queue that doesn't leak memory?
by hippo (Archbishop) on Feb 03, 2024 at 16:47 UTC | |
by LanX (Saint) on Feb 03, 2024 at 17:13 UTC | |
by eyepopslikeamosquito (Archbishop) on Feb 04, 2024 at 02:13 UTC | |
by Anonymous Monk on Feb 05, 2024 at 14:19 UTC |