The most idiomatic and most easily-understandable solution for "does a string contain any of these items" is:
if ( grep { $str =~ /$_/ } @arr ) { ... }
I ran the test again, with this new strategy added and a few other changes to the code:
- $str and @arr are each longer
- the matchword occurs in the middle of $str and @arr. This should make the solutions using first() more effective.
- some of the test names are changed to better describe what they do
Also, there is a small but important bug in your code:
first BLOCK, ARRAY
should be:
first BLOCK ARRAY
The former will only run the BLOCK once, regardless of outcome, and throw away the result. (Oh Perl syntax, why must you be so baroque?)
So how does the new method fare in this adjusted test?
word_altn 506/s
grep_block_index 2356/s was: block_grep
grep_expr_index 2373/s was: expr_grep
grep_block_regex 3957/s <-- new method here
first_index 4179/s was: list_util_index
first_regex 6871/s was: list_util_regex
The pleasant surprise is that a plain grep-regex solution turns out to be faster than replacing the regex with an
index() call. Replacing
grep() with
first() gives a further speedup of about 75%, but as we've just seen you lose some maintainability, and that can be important.
New code:
#!/bin/perl
use strict;
use warnings;
use List::Util qw( first );
use Benchmark qw( cmpthese timethese );
my @arr = qw( foo bar baz qux cool foo bar baz qux );
my $manywords = 'TONS OF WORDS ' x 500;
my $str = $manywords . 'I am cool ' . $manywords;
my @invocation;
my $results = timethese(
0,
{
'word_altn' => sub {
local $" = '|';
if( $str =~ /@arr/ ) {
++$invocation[0]; # print "Matched\n"
}
},
'grep_block_index' => sub {
if( grep { index($str, $_) !=-1 } @arr) {
++$invocation[1]; # print "Matched\n"
}
},
'grep_expr_index' => sub {
if( grep index($str, $_) !=-1, @arr) {
++$invocation[2]; # print "Matched\n"
}
},
'first_index' => sub {
if( first { index($str, $_) != -1 } @arr ) {
++$invocation[3]; #print "Matched\n"
}
},
'first_regex' => sub {
if( first { $str =~ /$_/ } @arr ) {
++$invocation[4]; #print "Matched\n"
}
},
'grep_block_regex' => sub {
if( grep { $str =~ /$_/ } @arr ) {
++$invocation[5]; #print "Matched\n"
}
},
},
'none',
);
print "@invocation\n";
die unless grep { $_>0 } @invocation == @invocation;
cmpthese $results;