If there is a stack penalty, it is not terrible, as the routine get
faster with large arrays:
use Benchmark qw(:all) ;
my @a;
push @a, int (rand(100)) foreach 1..2_000_000;
my %unique;
my (@awd1, @awd2, @awd3);
cmpthese(5, {
'jc' =>
sub { foreach my $thingy (@a) { $unique{$thingy} = 1
+; }
@awd1 = keys %unique;
},
'mk' =>
sub { @unique{ @a} = 1;
@awd2 = keys %unique;
},
'ys' =>
sub { @unique{ @a} = ();
@awd3 = keys %unique;
},
});
yields
Benchmark: timing 5 iterations of jc, mk, ys...
jc: 19 wallclock secs (16.75 usr + 0.35 sys = 17.10 CPU) @ 0
+.29/s (n=5)
mk: 6 wallclock secs ( 6.00 usr + 0.01 sys = 6.01 CPU) @ 0
+.83/s (n=5)
ys: 7 wallclock secs ( 6.00 usr + 0.00 sys = 6.00 CPU) @ 0
+.83/s (n=5)
s/iter jc mk ys
jc 3.42 -- -65% -65%
mk 1.20 185% -- -0%
ys 1.20 185% 0% --
The
= () optimization does not seem to make much difference.
-
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.