So, a lot of people like to say that. And indeed, sometimes index is ten times faster. But sometimes it's more than three times slower!
use Benchmark qw(:all);
$text = <<EOF;
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+aaaaaaaaaa
EOF
$pattern = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
cmpthese($count, {
'regex' => sub { $text =~ $pattern },
'index' => sub { index $text, $pattern },
});
__DATA__
Rate index regex
index 630601/s -- -67%
regex 1914815/s 204% --
Moreover, increasing the lengths of the text and pattern, I can make the regex be 40 times faster*. See Re^8: "advanced" Perl functions and maintainability for reasons why people use regexes instead of index. Personally, I still don't understand why there even is a difference in speed -- shouldn't the regex engine be optimized to notice that this is a search for a constant string and then call the same function as index?
*: No, I'm not kidding. The output follows. Moreover, for this example, adding a single study $text is an extra 10 times faster, completely obliterating index.
Rate index regex study
index 178/s -- -98% -100%
regex 7538/s 4124% -- -92%
study 98871/s 55311% 1212% --
Update: I'm running perl v5.8.5 built for i686-linux.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.