Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

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% --

Aaron B.
My Woefully Neglected Blog, where I occasionally mention Perl.


In reply to Re^3: Rewrite Program Using Arrays by aaron_baugher
in thread Rewrite Program Using Arrays by perl.j

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!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others browsing the Monastery: (10)
    As of 2014-09-23 18:54 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (239 votes), past polls