Reputation: 5247
I want to remove the entire array. Currently I do @array=();
Does it remove the elements and clears the memory , garbage collected? If not do i need to use Splice?.
Upvotes: 4
Views: 14918
Reputation: 385655
It's very very odd that you need to do this. Proper use of my
means it's very rare that one needs to empty an array.
@array = ();
will free the elements and call any destructors as necessary. In other words, the elements will be garbage collected (before the operation even ends) if they are not used elsewhere, as desired.
@array = ();
does not free the underlying array buffer. This is a good thing. undef @array;
would force the memory to be deallocated, which will force numerous allocations when you start putting more elements in the array.
So,
If you want free an array because you'll never use it again, limit its scope to where you need it by placing the my @array;
at the correct location.
{
my @array;
...
} # Elements of @array garbage collected here.
If you want to empty an array you will reuse, use @array = ();
.
my @array;
while (...) {
if (...) {
push @array, ...;
} else {
... use @array ...
@array = (); # Elements of @array garbage collected here.
}
}
Don't use undef @array;
.
You can use splice
if it's convenient.
say for @array;
@array = ();
could be written as
say for splice(@array);
Upvotes: 17
Reputation: 53
All these recipes didn't help me, but I found a new one:
my @tmp_arr = qw();
@array = @tmp_arr;
Upvotes: 0
Reputation: 66
If your goal is to release memory back to the OS you are probably out of luck. If your goal is to make the memory available to your perl program to use again then the other answers are all good.
For some more details check out the following links
http://www.perlmonks.org/?node_id=243025
In Perl, how can I release memory to the operating system?
Upvotes: 1
Reputation: 122383
@array = ();
is fine, you can also use
undef @array;
Note that this is wrong:
@array = undef;
it will have a value of undef
Upvotes: 4
Reputation: 4287
http://perldoc.perl.org/functions/undef.html
undef @array;
Should do what you need.
Upvotes: 0