I am unable to confirm your results. Why are you using both map and split in the first method? Why not a simple split which is much faster than either?

use warnings; use strict; use Benchmark; my $data=" this is a string example"; my @data; my $count = 100000; timethese($count, { 'map_split' => sub {@data=map { $_.="\n" } split (/\n/, $data);}, 'simple_split' => sub { @data = split "\n",$data; }, 'regex' => sub { @data= ( $data =~ /(.*?\n)/g );}, } ); __END__ Benchmark: timing 100000 iterations of map_split, regex, simple_split. +.. map_split: 2 wallclock secs ( 2.04 usr + 0.00 sys = 2.04 CPU) @ 48 +947.63/s (n=100000) regex: 2 wallclock secs ( 1.24 usr + 0.00 sys = 1.24 CPU) @ 80 +515.30/s (n=100000) simple_split: 1 wallclock secs ( 0.75 usr + 0.00 sys = 0.75 CPU) @ +132978.72/s (n=100000)

There is a mistake in the posted code. Your initial string is called $str when you initialise it, but $data when you split it.

Perhaps this typo influenced your results. If I run your code (with an empty $data variable) the regex indeed looks faster, but this is a completely spurious result.

$data = ''; Benchmark: timing 1000000 iterations of map_split, regex, simple_split +... map_split: 0 wallclock secs ( 0.99 usr + 0.00 sys = 0.99 CPU) @ 10 +09081.74/s (n=1000000) regex: 1 wallclock secs ( 0.54 usr + 0.00 sys = 0.54 CPU) @ 18 +48428.84/s (n=1000000) simple_split: 0 wallclock secs ( 0.94 usr + 0.00 sys = 0.94 CPU) @ +1062699.26/s (n=1000000)

Allowing warnings would have caught this mistake!

--
Regards,
Helgi Briem
helgi AT decode DOT is


In reply to Re: regex or split by helgi
in thread regex or split by mce

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.