#!perl -w use strict; use Benchmark qw/:all/; my $result = timethese( -5, { index => sub { -1 != index 'fooabc123', '123' }, regex => sub { 'fooabc123' =~ /123/ } } ); cmpthese $result; #### Benchmark: running index, regex for at least 5 CPU seconds... index: 6 wallclock secs ( 6.56 usr + -0.03 sys = 6.53 CPU) @ 8119742.77/s (n=53030040) regex: 5 wallclock secs ( 5.50 usr + 0.00 sys = 5.50 CPU) @ 4481230.91/s (n=24646770) Rate regex index regex 4481231/s -- -45% index 8119743/s 81% -- #### #!/usr/bin/perl use warnings; use strict; use Data::Dumper; use Benchmark qw/:all/; sub LCSRegEx { my $substr = $_[0]; my $len = length $_[0]; my $off = 0; while ($substr) { my @matches = grep /\Q$substr/, @_; last if @matches == @_; $off++; $len-- and $off=0 if $off+$len > length $_[0]; $substr = substr $_[0], $off, $len; } return $substr; } sub LCSIndex { my $substr = $_[0]; my $len = length $_[0]; my $off = 0; while ($substr) { my @matches = grep { -1 != index $_, $substr } @_; last if @matches == @_; $off++; $len-- and $off=0 if $off+$len > length $_[0]; $substr = substr $_[0], $off, $len; } return $substr; } my $result = timethese( -5, { LCSRegEx => sub { for ([ qw(fooabc123 fooabc321 foobca232) ], [ qw(abcfoo123 bcafoo321 foo123abc) ], [ qw(foo bor boz bzo) ]) { LCSRegEx(@{$_}); } }, LCSIndex => sub { for ([ qw(fooabc123 fooabc321 foobca232) ], [ qw(abcfoo123 bcafoo321 foo123abc) ], [ qw(foo bor boz bzo) ]) { LCSIndex(@{$_}); } } }); cmpthese $result; #### Benchmark: running LCSIndex, LCSRegEx for at least 5 CPU seconds... LCSIndex: 6 wallclock secs ( 5.28 usr + 0.00 sys = 5.28 CPU) @ 3463.93/s (n =18293) LCSRegEx: 6 wallclock secs ( 5.50 usr + 0.00 sys = 5.50 CPU) @ 916.36/s (n= 5040) Rate LCSRegEx LCSIndex LCSRegEx 916/s -- -74% LCSIndex 3464/s 278% --