I don't know where I got the idea in my brain that the global substitute expression was faster. It could very well be that I
figured that in some normal case, the difference didn't matter based upon some other benchmark.
I re-wrote your benchmark and yes, this does show that using 2 lines of Perl to do this is faster!
I show my code below..
use strict;
use warnings;
use Benchmark qw(cmpthese);
use Data::Dumper;
use List::Util qw(pairmap);
my @strings = (
no_trim_short => 'asd',
no_trim_mid => 'asdasdasdasdasdasdasd',
no_trim_long => 'asd' x 50,
no_trim_mid_with_ws => 'asd asd asd asd asd asd asd',
no_trim_long_with_ws => (join ' ', ('asd') x 20),
short => ' asd ',
mid => ' asdasdasdasdasdasdasd ',
long => ' '.('asd' x 20).' ',
mid_with_ws => ' asd asd asd asd asd asd asd ',
long_with_ws => ' '.(join ' ', ('asd') x 20).' ',
);
my @test_line_array = pairmap{$b}@strings;
#print "$_\n" for @test_line_array; #for debug
cmpthese (100000, {
global => sub{
my @copy = @test_line_array;
$_ =~ s/\A\s+|\s+\z//g foreach @copy;
},
global2 => sub{
my @copy = @test_line_array;
$_ =~ s/^\s+|\s+$//g foreach @copy;
},
twoLines => sub {
my @copy = @test_line_array;
s/\A\s+//, s/\s+\z// foreach @copy;
},
twoLines2 => sub {
my @copy = @test_line_array;
s/^\s+//, s/\s+$// foreach @copy;
},
dollar1 => sub {
my @copy = @test_line_array;
s/\A\s*(.*?)\s*\z/$1/ foreach @copy;
}
});
print "\n";
__END__
Rate global global2 dollar1 twoLines twoLines2
global 33681/s -- 0% -21% -68% -68%
global2 33681/s 0% -- -21% -68% -68%
dollar1 42662/s 27% 27% -- -60% -60%
twoLines 106610/s 217% 217% 150% -- -0%
twoLines2 106724/s 217% 217% 150% 0% --
-
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.