Lets time this
Code: Perl
use Benchmark qw(:all) ;
sub in_array_pradeep {
my ($arr,$search_for) = @_;
my %items = map {$_ => 1} @$arr;
return (exists($items{$search_for}))?1:0;
}
sub in_array_1 {
my ($arr,$search_for) = @_;
return grep {$search_for eq $_} @$arr;
}
sub in_array_2 {
my ($arr,$search_for) = @_;
foreach my $value (@$arr) {
return 1 if $value eq $search_for;
}
return 0;
}
my @arr = qw(Amlan Pradeep Shency Shabbir oleber or use subroutine references timethese benchmark running times of Perl code);
timethese(100000,
{
'in_array_pradeep' => sub {in_array_pradeep(\@arr, $_) foreach @arr},
'in_array_1' => sub {in_array_1(\@arr, $_) foreach @arr},
'in_array_2' => sub {in_array_2(\@arr, $_) foreach @arr},
});
and the results in my machine are:
Code:
Benchmark: timing 100000 iterations of in_array_1, in_array_2, in_array_pradeep...
in_array_1: 5 wallclock secs ( 5.34 usr + 0.00 sys = 5.34 CPU) @ 18726.59/s (n=100000)
in_array_2: 5 wallclock secs ( 4.48 usr + 0.00 sys = 4.48 CPU) @ 22321.43/s (n=100000)
in_array_pradeep: 32 wallclock secs (32.13 usr + 0.00 sys = 32.13 CPU) @ 3112.36/s (n=100000)
Now lets speak about the results.

The solution of pradeep is very slow. This seems obvious since he is creating a big structure in memory.
Now the other two are interesting.

The grep is fast since runs in C code inside the machine, but has to check all the elements.

The foreach stops when finds the first matching, so just half the match are needed in average.