Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Adding items to arrays: best approach?

by davido (Cardinal)
on May 28, 2020 at 14:38 UTC ( #11117422=note: print w/replies, xml ) Need Help??

in reply to Adding items to arrays: best approach?

Always let your commas trail. And I prefer having a comma even on the last element because then tomorrow when I add another element it's just a new line; I don't have to add a comma to the previous last line; my git diff is cleaner, and I'm less likely to forget.

If you are concerned about efficiency please understand that push behaves similarly to the C++ vector push_back method, which has an amortized time complexity of O(1). This is because as more space is allocated, the man behind the curtains asks for more than is needed immediately, predicting that more will be needed eventually. Here's a made up example:

@a = qw(a b c d e); # Array has 5 elements, with room for 10; push(@a, qw(f g h i j)); # Array has ten elements, with room for 10. push(@a, qw(k l m n o)); # Array has 15 elements with room for 30. New + memory had to be allocated, and array had to be moved into new, larg +er memory space. push(@a, qw(p q r s t)); # Array has 20 elements with room for 30. push(@a, qw(u v w x y)); # Array has 25 elements with room for 30. push(@a, qw(z 1 2 3 4)); # Array has 30 elements with room for 30. push(@a, qw(5 6 7 8 9)); # Array has to be moved to new memory. Array +has 35 elements with room for 70.

The formula for calculating how much extra space to allocate is not the same as what I demonstrated here. I just wanted to demonstrate that Perl allocates memory in chunks that allow for expansion, and only moves the array to a new, larger block when that future expansion memory in the current block has depleted.

Because the need to copy the entire array over to a larger memory block as the array expands only happens infrequently, despite the copy-over process being linear, the amortized time is constant; the copy-over fades into background noise.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11117422]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2021-01-27 07:24 GMT
Find Nodes?
    Voting Booth?