Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: How Perl can push array into array and then how retrieve

by jwkrahn (Monsignor)
on Nov 25, 2021 at 07:15 UTC ( #11139103=note: print w/replies, xml ) Need Help??


in reply to Re^2: How Perl can push array into array and then how retrieve
in thread How Perl can push array into array and then how retrieve

Or:

... my @f = map [$_+2, $_+1], 0 .. 5; ...

Replies are listed 'Best First'.
Re^4: How Perl can push array into array and then how retrieve
by cavac (Priest) on Nov 30, 2021 at 15:05 UTC

    On the downside, this would probably take me longer to understand than kcott's code when coming back to it after a year. Your solution is probably a lot faster, but for some strange reason i can never really wrap my head around map() (and similar functions) without looking at the perldoc.

    perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

      G'day cavac,

      "Your solution is probably a lot faster, ..."

      I've always found for to be faster than map so I benchmarked. I ran the following with: 0 .. 5 (from the two nodes on which you commented); 0 .. 40 (the OP's original range); and, 0 .. 5000 (just to see if a large range made any significant different).

      #!/usr/bin/env perl use strict; use warnings; use Benchmark 'cmpthese'; cmpthese 0 => { with_for => \&with_for, with_map => \&with_map, }; sub with_for { my @f; push @f, [$_+2, $_+1] for 0 .. 5; } sub with_map { my @f = map [$_+2, $_+1], 0 .. 5; }

      I ran each three times; there was little difference in the results; I've just posted the middle results below.

      # 0 .. 5 Rate with_map with_for with_map 602818/s -- -23% with_for 780657/s 30% -- # 0 .. 40 Rate with_map with_for with_map 92655/s -- -23% with_for 120756/s 30% -- # 0 .. 5000 Rate with_map with_for with_map 745/s -- -23% with_for 968/s 30% --

      The smallest difference was -21% vs. 27%; the largest was -25% vs. 33%. As the range was increased, all values tended towards -23% vs. 30% (the middle values for all runs).

      In this instance, for is faster than map (i.e. what I've always found in the past).

      — Ken

        Thanks for taking the time to benchmark this.

        perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139103]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2022-05-25 03:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (84 votes). Check out past polls.

    Notices?