Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Shrunk array takes more memory than original

by choroba (Cardinal)
on Nov 10, 2015 at 12:26 UTC ( #1147351=note: print w/replies, xml ) Need Help??


in reply to Shrunk array takes more memory than original

The only way how to shrink the memory is to allocate a new array (or undef, but then you can't keep any values after shrinking).
my @shrunk = @array[0 .. 5_000]; # Array slice. say size(\@shrunk); # 40072

See also How do I shrink an array in Perl? on StackOverflow.

لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Shrunk array takes more memory than original
by kroach (Pilgrim) on Nov 10, 2015 at 12:45 UTC

    I do not mean to shrink the memory, I would like it to stay the same instead of growing.

    I'm not adding anything new to the array and I don't get why it gets larger from having half of its elements removed.

      why it gets larger from having half of its elements removed.

      Because using $#array causes some magic to be attached to the array.

      You don't even have to assign to $#array for this to happen, only reference it:

      @b = 1 .. 10; print size \@b;; 256 print $#b; print size \@b;; 9 440

      And yes, 184 bytes does seem excessive. You'd think that the magic could be stored once and simply referenced for each array using an 4/8-byte pointer.


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
      In the absence of evidence, opinion is indistinguishable from prejudice.
        Because using $#array causes some magic to be attached to the array.
        Technically speaking, a temporary magic object is created that points to the array. When the object is assigned to, it truncates the array. This object is freed (well, returned to the pool anyway) at the end of the statement. The array itself never gains any magic.

        Dave.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2023-12-10 20:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (41 votes). Check out past polls.

    Notices?