Adding your optimization to BrowerUK's version, we get the best yet.
sub ikegami (@) {
my @a=@_;
my $i=@a;
my $n;
my $x;
map +( $n=rand($i--), $x=$a[$n], $a[$n]=$a[$i] )[1], @a
}
Rate naive listutil runrig broweruk ikegami
naive 636/s -- -6% -19% -26% -37%
listutil 675/s 6% -- -14% -21% -33%
runrig 785/s 23% 16% -- -9% -22%
broweruk 859/s 35% 27% 9% -- -15%
ikegami 1010/s 59% 50% 29% 18% --
Of course, this doesn't always help. For example, try shuffling somewhat long strings.
our @data = map { 'x' x 1000 } 1..1000;
cmpthese -3, { map { $_ => "$_ \@data" } qw/naive listutil broweruk ru
+nrig ikegami/ };
Rate runrig naive ikegami listutil broweruk
runrig 118/s -- -10% -40% -43% -86%
naive 131/s 11% -- -34% -37% -85%
ikegami 197/s 68% 51% -- -5% -77%
listutil 207/s 76% 58% 5% -- -76%
broweruk 860/s 632% 558% 336% 315% --
Update: runrig pointed out that my shuffle was broken. I changed $a[$n] to $x=$a[$n] to fix it. It slowed down my solution, but not by much.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|