$var = array(
1 => true;
3 => true;
7 => true
) if $var[$x] == true $var = '/^(1[238]?|3|6|7)$/'; if preg_match($var, $x) == true [edited by: g1smd at 6:28 pm (utc) on Feb 9, 2011]
use strict;
use Benchmark qw(:all);
timethese(10000000, {
'grep' => sub { my $x = 3; my $t = 1 if( grep { $x == $_ } (1, 3, 6, 7, 12,13, 18) ); },
'ifwithor' => sub { my $x = 3; my $t; $t = 1 if( ($x == 1)||($x == 3)||($x == 6)||($x == 7)||($x == 12)||($x == 13)||($x == 18) ); },
'array' => sub { my $x = 3; my @numbers = (1, 3, 6, 7, 12, 13, 18); my $t; foreach my $number (@numbers) { $t = 1 if ($x == $number); } },
'regexp' => sub { my $x = 3; my $t; $t = 1 if($x =~ m/^(1[238]?|3|6|7)$/) },
'hash' => sub { my $x = 3; my %numbers = (1 => 1, 3 => 1, 6 => 1, 7 => 1, 12 => 1, 13 => 1, 18 => 1); my $t; $t = 1 if ($numbers{ $x });},
});
perl test.pl
Benchmark: timing 10000000 iterations of array, grep, hash, ifwithor, regexp...
array: 38 wallclock secs (37.02 usr + 0.00 sys = 37.02 CPU) @ 270153.45/s (n=10000000)
grep: 18 wallclock secs (16.61 usr + 0.00 sys = 16.61 CPU) @ 602083.21/s (n=10000000)
hash: 51 wallclock secs (49.63 usr + 0.00 sys = 49.63 CPU) @ 201511.34/s (n=10000000)
ifwithor: 6 wallclock secs ( 5.37 usr + 0.00 sys = 5.37 CPU) @ 1860465.12/s (n=10000000)
regexp: 14 wallclock secs (13.14 usr + 0.00 sys = 13.14 CPU) @ 761035.01/s (n=10000000)
'do_later' => sub
{
my $x = 18;
my $t;
my @numbers = (1, 3, 6, 7, 12, 13, 18);
my $i = -1;
do
{
$i++;
$t = 1;
} until ($x == $numbers[$i] || $i >= scalar @numbers);
},
'do_early' => sub
{
my $x = 3;
my $t;
my @numbers = (1, 3, 6, 7, 12, 13, 18);
my $i = -1;
do
{
$i++;
$t = 1;
} until ($x == $numbers[$i] || $i >= scalar @numbers);
},
'do_never' => sub
{
my $x = 20;
my $t;
my @numbers = (1, 3, 6, 7, 12, 13, 18);
my $i = -1;
do
{
$i++;
$t = 1;
} until ($x == $numbers[$i] || $i >= scalar @numbers);
},
'precompile_regex' => sub
{
my $x = 18;
my $t;
my $num_regex = qr(^(1[238]?|3|6|7)$);
if($x =~ m/$num_regex/)
{
$t = 1;
}
},