in reply to slow CGI's

I don't know to what extent Perl is optimised, but I suppose accessing a member of an array is somewhat slower than accessing a private variable. And especially if the indexing takes place inside a loop. So how about this:

if ( defined($array[0]) ) { my $array0 = $array[0]; foreach ( @numbers ) { next unless $array0 == $_; print "FOUND<p>"; } }

--bwana147

Replies are listed 'Best First'.
Re: Re: slow CGI's
by chromatic (Archbishop) on Jul 07, 2003 at 18:14 UTC

    I downvoted this node because I think it is an inappropriate suggestion. Rule #1 of benchmarking is don't guess. Rule #2 of benchmarking is optimize what really matters.

    The biggest potential problem I can see with this code (without seeing the data set) is that the loop tends to O(n/2) performance. If there are a lot of numbers in the array, it will take a while to find the right number. A hash lookup, tending to O(1) performance, would be much more performant.

      Interestingly, benchmarks do not bear this assumption out. (perl 5.8.0 on a celeron lots of other stuff going on at the same time, but tried multiple times, very similar results).
      #!/usr/local/bin/perl use Benchmark; for (1.. 100000) { $rand = rand * 100; push @rvs, $rand; $last = $rand; } $array[0] = $rand; timethese ( 100, {grepit => \&grepit, hashit => \&hashit}); sub grepit { return 1 if (grep /$array[0]/, @rvs); } sub hashit { @hash{@rvs} = (1) x @rvs; return 1 if ($hash{$array[0]}); }
      Benchmark: timing 100 iterations of grepit, hashit... grepit: 19 wallclock secs (19.36 usr + 0.03 sys = 19.39 CPU) @ 5.16/s (n=100) hashit: 28 wallclock secs (27.84 usr + 0.04 sys = 27.88 CPU) @ 3.59/s (n=100) the number is 0.359661571026372 Grepit found the number Hashit found the number