Hmm. Sorry to be the parade-rainer, but the benchmark isn't actually measuring what it should be. @x is a lexical here, and when Benchmark takes those strings and evaluates them, @x is out of scope. That's why they're all going so fast; there's nothing to loop over.

Also, and more minorly, your for_index_substr routine isn't working -- $_ is being re-aliased on the second for loop and the actual target string is being lost.

I took the liberty of making a couple of changes and re-running:

use strict; use Benchmark qw(cmpthese); my @x; my @result; $x[0]= "mark " x 35; $x[1]= "asdfasdfasdfasdfasdf " x 35; $x[2]= "as " x 31; $x[3]= "asdfasdfasdfasdfasdfasdf " x 100; $x[4]= "asdfasdfasdfasdfasdfasdf " x 10; cmpthese (-5, { 'regexp' => sub { my $i; foreach (@x) { /^((?:\S+\s*){1,30})/; $result[$i++]{REx} = $1; } }, 'split_join' => sub { my $i; foreach (@x) { $result[$i++]{split} = join " ", (split " ", $_,31)[0..29]; } }, 'for_index_substr' => sub { my $i; foreach (@x) { my $ind = index ($_, " "); for my $foo (0..28) { last if $ind == -1; $ind = index $_, " ", $ind + 1; } $result[$i++]{index} = substr($_,0,$ind); } }, } ); for (@result) { print "bad!" unless ($_{REx} eq $_{split} and $_{split} eq $_{index}); }

This produces:

                   Rate       split_join for_index_substr           regexp
split_join       4294/s               --              -7%             -27%
for_index_substr 4618/s               8%               --             -21%
regexp           5849/s              36%              27%               --

-dlc


In reply to (dchetlin: Benchmark fixes) 30 Spaces- 1 question by dchetlin
in thread 30 Spaces- 1 question by AgentM

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.