- Is there any efficiency advantage in either approach?
- Does the hash size make a difference?
- How about when done 5000 times for different $input values?
I personally believe that there's no significative advantage of one approach over the other but possibly in terms of personal tastes. As far as efficiency is concerned, what do you mean? Speed of execution? If so, then I wouldn't mind, since it's such a tiny difference, but you may answer your question(s) yourself with Benchmark.pm!
I notoriously suck at benchmarks, doing continuous errors, (which are generally pointed out by others...) but here's my try anyway:
#!/usr/bin/perl use strict; use warnings; # use 5.010; use Benchmark qw/cmpthese :hireswallclock/; { my @chr=('a'..'z', 'A'..'Z'); sub genkeys { map { join '' => map $chr[rand @chr], (1) x (5 + rand 10); } 1..shift; } } my %hash=map {$_ => 1} genkeys 5000; my @test=(keys %hash, genkeys 5000); { $|++; local $\="\n"; open my $fh, '>', '/dev/null' or die "Can't open /dev/null: $!\n"; cmpthese -60 => { assign => sub () { for my $input (@test) { if (my $ans = $hash{$input}) { print $fh "$input => $ans"; } } }, double => sub () { for my $input (@test) { if (exists $hash{$input}) { print $fh $hash{$input}; } } } }; } __END__
As I expected, as it is it doesn't show any noticeable difference.
kirk:~ [15:16:04]$ ./bm.pl Rate double assign double 29.4/s -- -1% assign 29.7/s 1% --
Indeed I generally refrain from the temptation of doing benchmarks "like this" when someone suggests them, and even tend to slightly bash those who do: this time I was curious to see if at least a tiny systematic difference would have arisen, but that doesn't seem to be the case: feel free to modify it the way you like most though!
In reply to Re^2: the if statement
by blazar
in thread the if statement
by kwn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |