Well, you could get rid of your loop by using map, but my benchmark shows no gain there. Eliminating some intermediate variables does speed things up, though. If you get rid of @words and $word completely, you'll gain some time, regardless of which looping method you use:
#!/usr/bin/env perl
use Modern::Perl;
use Benchmark qw(:all);
# create a line with words and spaces to split on
my $line = '';
$line .= ('a', 'b', 'c', 'd', ' ')[rand(5)] for (1..1000);
cmpthese( 100000, {
'loop with vars' => \&loopwithvars,
'loop sans vars' => \&loopsansvars,
'with map' => \&withmap,
});
sub loopwithvars {
my %wordcount;
my @words = split ' ', $line;
for my $word (@words){
$wordcount{$word}++;
}
}
sub loopsansvars {
my %wordcount;
for (split ' ', $line){
$wordcount{$_}++;
}
}
sub withmap {
my %wordcount;
map { $wordcount{$_}++ } split ' ', $line;
}
###### results ######
Rate loop with vars with map loop sans vars
loop with vars 11338/s -- -15% -17%
with map 13369/s 18% -- -2%
loop sans vars 13624/s 20% 2% --
-
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.
|