in reply to Benchmark of hash emptiness test
I can't answer your question, however it is interesting to consider the two cases:
use strict; use warnings; use Benchmark qw(cmpthese); my $HASHSIZE = 1e3; my %hash; test (); @hash{1..$HASHSIZE} = () x $HASHSIZE; test (); sub test { my $_keys = keys %hash; my $_scalar_keys = scalar(keys %hash); my $_scalar = scalar(%hash); my $_if = %hash; print "_keys: $_keys\n"; print "_scalar_keys: $_scalar_keys\n"; print "_scalar: $_scalar\n"; print "_if: $_if\n"; cmpthese(-1, { _keys => sub {if (keys %hash) { ; }}, _scalar_keys => sub {if (scalar(keys %hash)) { ; }}, _scalar => sub {if (scalar(%hash)) { ; }}, _if => sub {if (%hash) { ; }}, } ); }
Prints:
_keys: 0 _scalar_keys: 0 _scalar: 0 _if: 0 Rate _scalar _if _keys _scalar_ +keys _scalar 5217686/s -- -10% -15% +-18% _if 5766838/s 11% -- -6% +-10% _keys 6136894/s 18% 6% -- + -4% _scalar_keys 6387143/s 22% 11% 4% + -- _keys: 1000 _scalar_keys: 1000 _scalar: 629/1024 _if: 629/1024 Rate _scalar _if _keys _scalar_ +keys _scalar 379905/s -- -1% -92% +-92% _if 384350/s 1% -- -92% +-92% _keys 4930608/s 1198% 1183% -- + -1% _scalar_keys 4996935/s 1215% 1200% 1% + --
Note that I prefer to use cmpthese and that unless really huge numbers of tests are made without anything much else going on, the time is sufficiently small as to not matter anyway.
|
|---|