snowcrash has asked for the wisdom of the Perl Monks concerning the following question:

hi fellow monks!

please explain the enormous difference in computation time for the following two statements:
my @data = ( 0 .. 50000); my %hash = () ; ### version 1 map { $hash{$_}++ } @data; ### version 2 %hash = map { $_ => 1 } @data; ### version 3 ### as fast as version 1 %hash = map { $_ => } @data
version 1 is about 100 times faster on my machine... i'm running 5.005_03 built for i386-linux.

thanks,
snowcrash //////

Replies are listed 'Best First'.
(tye)Re: map efficiency
by tye (Sage) on Jan 31, 2001 at 00:17 UTC

    Turn on warnings and you'll probably realize that trailing commas are silently ignored and that => is a "fat comma".

    With warnings, your last example complains "Odd number of elements in hash assignment" and doesn't do what you thought.

    It is a "bug" that map is too slow when more than one item is output per input item. This bug will be fixed when perl 5.6.1 or perl 5.8 becomes available.

            - tye (but my friends call me "Tye")
Re: map efficiency
by japhy (Canon) on Jan 31, 2001 at 00:17 UTC
    Because the second two are making a rather large list and copying it over to a hash. That sounds like it would take a bit of work.

    japhy -- Perl and Regex Hacker
A reply falls below the community's threshold of quality. You may see it by logging in.