Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^2: shift v. indexing into an array

by ikegami (Patriarch)
on Nov 15, 2009 at 22:34 UTC ( [id://807314]=note: print w/replies, xml ) Need Help??


in reply to Re: shift v. indexing into an array
in thread shift v. indexing into an array

perl arrays keep a "start-of-array" number in their datastructures, so using shift() usually doesn't move any items at all and it's generally pretty efficient to shift() even very large arrays.

shift never moves any items, and thus it's extremely efficient no matter the size of the array.

@a = qw( a b c ); +---+---+---+---+ @a = | a | b | c | X | ( X = spare ) +---+---+---+---+ ^ ^ | | start end shift @a; +---+---+---+---+ @a = | X | b | c | X | +---+---+---+---+ ^ ^

I'm assuming shift/push combos move stuff around every once in a while, since I write code that depends on that behaviour and it seems to work, but I'm only 90% certain on that.

It's not the shift/push combo, it's push alone that causes the moving.

For efficiency, arrays can have more elements allocated than necessary. If a push is performed, these spare elements will be used. If a push is performed and there no spare elements, a new bigger array is allocated and the elements (pointers) are moved to the new array. This occurs whether shift was used or not.

[ continuing from above ] push @a, 'd'; +---+---+---+---+ @a = | X | b | c | d | +---+---+---+---+ ^ ^ push @a, 'e'; -> No more space! Re-allocation occurs. -> $new_buf_size = $old_buf_size * 2 + 4 -> Pointers to elements are quickly copied to newly allocated buffer. +---+---+---+---+ | X | b | c | d | +---+---+---+---+ / / / / / / / / / v v v +---+---+---+---+---+---+---+---+---+---+---+---+ @a = | b | c | d | e | X | X | X | X | X | X | X | X | +---+---+---+---+---+---+---+---+---+---+---+---+ ^ ^

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-04-24 22:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found