Skip to content

Instantly share code, notes, and snippets.

@Getty
Created February 28, 2012 20:57
Show Gist options
  • Save Getty/1935072 to your computer and use it in GitHub Desktop.
Save Getty/1935072 to your computer and use it in GitHub Desktop.
Benchmarking Regexp vs. Grep vs. Hash for "finding"
#!/usr/bin/env perl
use Benchmark qw( cmpthese );
my %in = (
bar => 1,
baz => 1,
foo => 1,
);
my %out = (
bar => 1,
baz => 1,
boo => 1,
);
cmpthese(
10_000_000,
{ 'Grep' => sub {
grep { $_ eq 'foo' } qw(bar baz foo);
},
'!Grep' => sub {
grep { $_ eq 'foo' } qw(bar baz boo);
},
'Regexp' => sub { 'foo' =~ m/bar|baz|foo/ },
'!Regexp' => sub { 'foo' =~ m/bar|baz|boo/ },
'Hash' => sub { defined $in{foo} },
'!Hash' => sub { defined $out{foo} },
}
);
__END__
Rate Regexp Grep !Grep Hash !Regexp !Hash
Regexp 181192/s -- -69% -70% -91% -91% -93%
Grep 583771/s 222% -- -4% -72% -73% -79%
!Grep 609756/s 237% 4% -- -71% -71% -78%
Hash 2114165/s 1067% 262% 247% -- -0% -23%
!Regexp 2123142/s 1072% 264% 248% 0% -- -22%
!Hash 2732240/s 1408% 368% 348% 29% 29% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment