Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: '%hash = ()' is slower than 'undef %hash'

by shmem (Chancellor)
on May 18, 2018 at 11:17 UTC ( #1214837=note: print w/replies, xml ) Need Help??

in reply to '%hash = ()' is slower than 'undef %hash'

The assignment of an empty list erases the content of %hash, but undef %hash erases the container. So these are different operations to choose from for the task at hand.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: '%hash = ()' is slower than 'undef %hash'
by rsFalse (Friar) on May 18, 2018 at 12:01 UTC
    What is the biggest difference we can obtain by using these two? I really don't understand :(
      What is the biggest difference we can obtain by using these two?

      The difference can be seen with Devel::Peek:

      #/usr/bin/perl use Devel::Peek; use feature 'say'; my %assign = ( foo => 1234, bar => 5678, ); my %undef = ( foo => 1234, bar => 5678, ); %assign = (); undef %undef; say "%assign (",\%assign,") after assignment:"; Dump(%assign); say "%undef (",\%undef,") after undef:"; Dump(%undef); __END__ %assign (HASH(0x195f890)) after assignment: SV = PVHV(0x193fe60) at 0x195f890 REFCNT = 1 FLAGS = (PADMY,SHAREKEYS) ARRAY = 0x19a1d70 KEYS = 0 FILL = 0 MAX = 7 %undef (HASH(0x195f860)) after undef: SV = PVHV(0x193fe80) at 0x195f860 REFCNT = 1 FLAGS = (PADMY,SHAREKEYS) ARRAY = 0x0 KEYS = 0 FILL = 0 MAX = 7

      The difference lies in the ARRAY element of the above output. By assignment of an empty list the container of the key/value pairs is preserved, whereas undef erases it and sets it to a NULL pointer.

      It is obviously cheaper to just wipe the container (and its content) instead of iterating through it and re-arranging its internal structure. - edit - see below, what dave_the_m writes.

      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
      The effect on the hash is indistinguishable, as far as I can say. But the two expressions have different values: %hash = () returns an empty hash, whereas undef %hash returns undef. This isn't a big deal, but in my opinion big enough to keep the two distinct.
      I think defined %hash used to show the difference . Unfortunately it's deprecated now.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2019-10-16 07:11 GMT
Find Nodes?
    Voting Booth?