Why s/^\s+|\s*$/g rather than s/^\s+|\s+$/g, s/^\s*|\s*$/g or s/^\s*|\s+$/g?

A benchmark suggests the two substitution approach is faster than any of the single substitution approaches and that there are interesting variations between the different single substitution options:

use strict; use warnings; use Benchmark qw(cmpthese); my $str = (' ' x 1000) . ('x' x 100000) . (' ' x 1000); cmpthese ( -5, { plusplus => \&plusplus, starstar => \&starstar, starplus => \&starplus, plusstar => \&plusstar, twosub => \&twosub, } ); print "\n\nString got clobbered\n" if $str !~ /^ .* $/; sub plusplus { $_ = $str; s/^\s+|\s+$//g; } sub starstar { $_ = $str; s/^\s*|\s*$//g; } sub starplus { $_ = $str; s/^\s*|\s+$//g; } sub plusstar { $_ = $str; s/^\s+|\s*$//g; } sub twosub { $_ = $str; s/^\s+//; s/\s*$//; }
Rate starstar plusstar plusplus starplus twosub starstar 47.0/s -- -8% -25% -28% -42% plusstar 51.2/s 9% -- -18% -21% -37% plusplus 62.5/s 33% 22% -- -4% -23% starplus 65.1/s 39% 27% 4% -- -20% twosub 81.6/s 74% 59% 31% 25% --

The benchmark uses a single large string (100_000 characters) with a fairly large run of spaces (1000) at the start and end.


DWIM is Perl's answer to Gödel

In reply to Re^3: performance enhancement by GrandFather
in thread performance enhancement by alandev

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.