in reply to push to array without copying
The down-side of using references is that dereferencing stuff in multiple places can a) get messy; b) actually end up costing more time than simply duplicating the data and avoiding the dereferencing, if the data items are small.
The hash won't be used once the array is created, so I'm not concerned about the hash values being modified when the array values are.
That observation if key here. If you don't need the values in the hash after you've copied them to the array, don't copy them, move them.
That can be achieved by deleteing the key/value pair from the hash and assigning the return from delete -- which is the value of the key being deleted -- to the array.
Like this:
my %hash = ('a'=>'test'); my @arr = delete $hash{'a'}; print $arr[0]."\n";
This results in the key 'a' being removed from the hash, and its former value 'test' being transfered directly to $arr[0] without any copying.
I assume that would be faster?
It will be; provided: a) the size of the values is sufficient to make a noticeable difference -- a few hundred bytes would do it -- and b) it doesn't force you to do too much extra work other places as a result.
delete also works with hash slices, which makes this very convenient and efficient for doing multiple transfers simultaneously:
%h = qw[ the quick black fiend jumps over the lazy god child ];; pp \%h;; { black => "fiend", god => "child", jumps => "over", the => "lazy" } print delete @h{ qw[ the black god ] };; lazy fiend child pp \%h;; { jumps => "over" }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: push to array without copying
by chris212 (Scribe) on Nov 15, 2016 at 17:39 UTC | |
by BrowserUk (Patriarch) on Nov 15, 2016 at 21:51 UTC | |
by chris212 (Scribe) on Nov 16, 2016 at 18:39 UTC |