in reply to Re: Quickly finding an element in an array
in thread Quickly finding an element in an array

Thanks, I've modified my code to use this, but surprisingly perl is dumping core (5.005_03 on FreeBSD and 5.6.1 on Solaris). This is a different problem, but I'm really surprised it's happening. Does anyone know why? Here's some code that reproduces the problem:

#!/usr/bin/perl -Tw use strict; use Benchmark; my @array; foreach (1..1000) { push @array, 1 + int rand 199; } my @start = (0, @array); my @end = (@array, 0); my @middle = @array; splice(@middle, 500, 0, 0); timethese(1000, { 'grep_middle' => sub { my $found = 0; grep {$_ == 0 and $found = 1 and last} @middle; }, 'foreach_middle' => sub { my $found = 0; foreach (@middle) { $_ == 0 and $found = 1 and last; } }, 'hash_middle' => sub { my $found = 0; my %hash = map { $_ => undef } @middle; $found = 1 if exists $hash{0}; } });

Replies are listed 'Best First'.
Re: Re: Re: Quickly finding an element in an array
by blakem (Monsignor) on Jan 08, 2002 at 01:56 UTC
    The bare block around the grep is important... Change this line:
    grep {$_ == 0 and $found = 1 and last} @middle;
    To:
    { grep {$_ == 0 and $found = 1 and last} @middle; }
    And I get:
    Benchmark: timing 1000 iterations of foreach_middle, grep_middle, hash +_middle... foreach_middle: 1 wallclock secs ( 0.80 usr + 0.00 sys = 0.80 CPU) +@ 1250.00/s (n=1000) grep_middle: 3 wallclock secs ( 3.09 usr + 0.00 sys = 3.09 CPU) @ 3 +23.62/s (n=1000) hash_middle: 30 wallclock secs (26.40 usr + 0.02 sys = 26.42 CPU) @ 3 +7.85/s (n=1000)

    -Blake