in reply to Re: Re: Re: Re: Zip Code Script
in thread Zip Code Script

Show your code. Please include the building of the hash in that code, since that was the cost I was looking at: one linear scan of an array, vs one hash lookup in a hash built from that same data.

I'd be incredibly surprised if there was ever a time when building the hash would ever be faster. I mean, it goes back to my "how much info did you throw away at the end?" theory that I talked about here some time ago.

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Re: Zip Code Script
by Fastolfe (Vicar) on Dec 13, 2000 at 01:25 UTC
    I am building the hash in the test, but I left the construction of the array outside of it:
    use Benchmark qw{ timeit timediff timestr }; use strict; my @array; for (1 .. 10) { push(@array, $_); my $time = timeit(500000, "&search_array($_)"); my $time2 = timeit(500000, "&search_hash($_)"); printf("%2d %s\n", $_, timestr timediff($time, $time2)); } sub search_array { my $max = shift; my $item; my $looking = int(rand($max)); foreach $item (@array) { return 1 if $item == $looking; } return; } sub search_hash { my $max = shift; my %hash; @hash{@array} = (); return 1 if exists $hash{rand($max)}; return; }
    Actually this sucks. I made some stuff more readable and my results now differ from what I was seeing earlier. I can't reproduce my old results. So yah, it looks like you're right. It's an increasing trend in favor of a linear search. My bad.