Nor, is it fair that in the 'slow' one, you use a temporary array...
EvanCarroll is right about the slight differences in the routines, so I commented out some things in code and made them both use the same array (note, I increased the number of elements to look for as well as the number of iterations for more meaningful results):
#!/usr/bin/perl -w
use strict;
use Benchmark qw(:all);
my @choices = qw|a b c z m p t l c f g|;
my %choices = map{$_=>1}@choices;
my @cData = <DATA>;
timethese(50_000,{'Damn Slow'=>\&parseData1,
'Much Better'=>\&parseData2});
sub parseData1 {
foreach (@cData){
chomp;
my @items = split/,/,$_;
#slow way,
foreach my $item (@items){
if(grep {$item eq $_} @choices){
#print qq|FOUND $item|;
}
}
}
}
sub parseData2 {
foreach(@cData){
chomp;
# foreach my $item (split/,/,$_){
my @items = split/,/,$_;
#slow way,
foreach my $item (@items){
if ($choices{$item}){
#print qq|FOUND $item\n|;
}
}
}
}
__DATA__
z,t,m,u,a,b,c
s,t,l,m,z,a,s
c,b,a,m,u,t,n
k,l,t,s,z,r,t
Which still produces:
perl seediff.pl
Benchmark: timing 50000 iterations of Damn Slow, Much Better...
Damn Slow: 6 wallclock secs ( 6.12 usr + 0.00 sys = 6.12 CPU) @ 81
+72.61/s (n=50000)
Much Better: 3 wallclock secs ( 2.96 usr + 0.00 sys = 2.96 CPU) @ 1
+6874.79/s (n=50000)
I think the above changes were 'fair' since the performance of a function like SQL in() in an actual database should not decrease noticeably with the number of elements.
Celebrate Intellectual Diversity
-
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.