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

Re: How to duplicate every member of an array

by davido (Cardinal)
on Jul 28, 2022 at 15:01 UTC ( [id://11145811]=note: print w/replies, xml ) Need Help??


in reply to How to duplicate every member of an array

List::Util is a core module (ships with Perl). It provides the mesh() function, which can be used as follows:

my @doubled = mesh \@array, \@array;

It turns out to be really quick.

#!/usr/bin/env perl use v5.36; use strict; use warnings; use Benchmark qw(cmpthese); use List::Util qw(mesh); my @array = ('a' .. 'z'); cmpthese( -5, { mapped => \&mapped, meshed => \&meshed, }, ); sub mapped { return [map {$_,$_} @array]; } sub meshed { return [mesh \@array, \@array]; }

The output:

Rate mapped meshed mapped 111262/s -- -51% meshed 226692/s 104% --

When I bump it up to 676 elements ('aa' .. 'zz'), the comparison is similar:

Rate mapped meshed mapped 4157/s -- -50% meshed 8262/s 99% --

With 11756 elements ('aaa' .. 'zzz') the ratio holds.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2025-12-12 16:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (92 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.