Grinnz / Perl-Critic-Community

Perl::Critic::Community - Community-inspired Perl::Critic policies
https://metacpan.org/pod/Perl::Critic::Community
Other
8 stars 10 forks source link

if (%bar) {} Is Probably Not A Good Suggestion #19

Closed zoffixznet closed 9 years ago

zoffixznet commented 9 years ago

The suggestion to use if (%bar){} here should probably be replaced with if (keys %bar){}, as using a hash directly for this purpose is several orders of magnitude slower in some instances. Perl seems to be optimized to deal with the specific case of if (%hash){}, but the performance drops dramatically for, say, using unless, which isn't present with the keys %hash variant:

zoffix@:~$ perl -Mojo -wlE 'my %h = 1..1000_000; n { for(1..100){ unless(%h ){} } } 100'
4.80698 wallclock secs ( 4.79 usr +  0.01 sys =  4.80 CPU) @ 20.83/s (n=100)
zoffix@:~$ perl -Mojo -wlE 'my %h = 1..1000_000; n { for(1..100){ unless(keys %h){} } } 100'
0.000820875 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)