in reply to "exists $hash{key}" is slower than "$hash{key}"

Hi

Just a very wild guess (Disclaimer: I didn't check your benchmark for possible holes)

It seems to me that exists is just implemented on top of retrieving the value.

IOW the opcode for exists gets the value but throws it away, which makes it more expensive than a normal look-up.

C:\WINDOWS\system32>perl -MO=Concise -E"exists $h{a}" 4 <@> leave[1 ref] vKP/REFC ->(end) 1 <0> enter ->2 2 <;> nextstate(main 74 -e:1) v:%,{,469764096 ->3 - <1> ex-exists vK/1 ->4 3 <+> multideref($h{"a"}) vK/EXISTS ->4 - <0> ex-gv s ->3 -e syntax OK C:\WINDOWS\system32>perl -MO=Concise -E"$h{a}" 4 <@> leave[1 ref] vKP/REFC ->(end) 1 <0> enter ->2 2 <;> nextstate(main 74 -e:1) v:%,{,469764096 ->3 - <1> ex-helem vK/2 ->4 3 <+> multideref($h{"a"}) vK ->4 - <0> ex-gv s ->3 -e syntax OK

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Replies are listed 'Best First'.
Re^2: "exists $hash{key}" is slower than "$hash{key}"
by swl (Prior) on Jan 06, 2020 at 00:57 UTC

    If this is the case then it seems counter intuitive at first glance, and maybe is something that could be modified.

    One advantage of using exists $hash{$key} is that the hash values can then all be assigned undef, potentially saving memory. (Although one could also create a scalar ref and re-use it, e.g. my $flag = \1 - this is what is used in Hash::Ordered as a tombstone value.

      > If this is the case then it seems counter intuitive at first glance, and maybe is something that could be modified.

      Well - "if this is the case" - it's most probably for "historical reasons".

      I could imagine exists came later and that was the easiest way to implement it, and the pay off for any redesign is too small.

      You shouldn't forget that there is much more going on in the background which would need to be replicated, like autovivification and so on.

      > One advantage of using exists

      I'm not sure I can follow.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

        Yes, I assume the code is written this way for good historical reasons. These reasons might no longer apply or be out-weighed by other factors, but I don't know enough to be able to say if any change would be worthwhile.

        The advantage of exists over checking values is tangential to the main point of the post. It's about memory usage - if one re-uses the same SV across hash values then that takes less memory than using a new SV for each hash value. It's another case where one needs a very large number of hash entries for it to make a meaningful difference, but there are times when this applies.