sflitman has asked for the wisdom of the Perl Monks concerning the following question:
I was wondering whether it made sense to write things like if (index($options,'checkboxes')>-1) {...} instead of if ($options=~/checkboxes/) {...} for speed. So I whipped up this little benchmark:
As you can see, regexp is about twice as fast as using index for running 100 failed matches of fixed text against a single text. I am aware of Regexp::List but wanted to use something which tests unoptimized Perl for really single cases.#!/usr/bin/perl # regindbench - which is faster, regexp for fixed text patterns or ind +ex()? use strict; use Benchmark qw/:all/; sub random { int rand shift } my @letters=('A'..'Z'); my $nLetters=scalar @letters; my $text=join('',map { $letters[random($nLetters)] } 0..9999); # 10 +,000 chars my ($pat,@pats); map { do { $pat=join('',map { $letters[random($nLetters)] } 0..4); # 5 cha +r patterns } until index($text,$pat)==-1; # which never match push @pats,$pat; } 0..99; sub via_regexp { map { die "via_regexp $_ found\n" if $text=~/$_/ } @pats; } sub via_index { map { die "via_index $_ found\n" if index($text,$_)>-1 } @pats; } cmpthese(100000,{regexp=>\&via_regexp,index=>\&via_index}); exit; __END__ Perl 5.8.8 using 100000 iterations on a 3 GHz 64-bit Intel QuadCore running Fedora Core 7 (6000 bogomips per core) Rate index regexp index 370/s -- -47% regexp 695/s 88% --
If I add study $text, there is a fairly impressive improvement, but then again I'm not going to be using study for every comparison:
What do my fellow monks think? Shouldn't regexp have more overhead than a simple strstr? Or is this that Magic we keep hearing about? ;-)study $text; # added before call to cmpthese above Rate index regexp index 364/s -- -71% regexp 1274/s 250% --
SSF
|
---|
Back to
Seekers of Perl Wisdom