in reply to Re: Re: Generating an array of n identical elements
in thread Generating an array of n identical elements

Not certain that its exactly a great Benchmark, but it seems to clearly indicates that using the x op is substantially faster.

#! perl -sw use strict; use Benchmark qw(cmpthese); sub mapgen { return map $_[0], (1..$_[1]); } sub xgen { return ($_[0]) x $_[1]; } cmpthese( 1000, { mapgen => 'my @ones = mapgen 1, 1000;', xgen => 'my @ones = xgen 1, 1000;', }); __END__ Benchmark: timing 1000 iterations of mapgen, xgen... mapgen: 9 wallclock secs ( 8.18 usr + 0.00 sys = 8.18 CPU) @ 12 +2.23/s (n=1000) xgen: 5 wallclock secs ( 5.15 usr + 0.00 sys = 5.15 CPU) @ 19 +4.29/s (n=1000) Rate mapgen xgen mapgen 122/s -- -37% xgen 194/s 59% -- C:\test>

Well It's better than the Abottoire, but Yorkshire!

Replies are listed 'Best First'.
Re: Re: Re: Re: Generating an array of n identical elements
by bronto (Priest) on Sep 16, 2002 at 10:49 UTC

    Right. And using fixed values instead of generic subroutines appears to be much more (and more and more) fast:

    #! perl -sw use strict; use Benchmark qw(cmpthese); my $mapgen = sub { return map 5, (1..1000); } ; my $xgen = sub { return (5) x 1000 ; } ; cmpthese( 10000, { mapgen => $mapgen, xgen => $xgen, }); __END__

    gives, on my lightly-loaded Pentium IV 1.5Ghz,

    Benchmark: timing 10000 iterations of mapgen, xgen... mapgen: 5 wallclock secs ( 5.04 usr + 0.03 sys = 5.07 CPU) @ 19 +72.39/s (n=10000) xgen: 0 wallclock secs ( 0.03 usr + 0.00 sys = 0.03 CPU) @ 33 +3333.33/s (n=10000) (warning: too few iterations for a reliable count) Rate mapgen xgen mapgen 1972/s -- -99% xgen 333333/s 16800% --

    So map loses again. Uhm... it's the second time that other functions are far faster than map... I'd be interested in seeing a real case where map is the faster choice... does anyone have any?

    Ciao!
    --bronto

    # Another Perl edition of a song:
    # The End, by The Beatles
    END {
      $you->take($love) eq $you->made($love) ;
    }

      my @new = map { transform $_ } @old; is faster than
      my @new; push @new, transform $_ for @old;
      I'm wary of your results though. My gut feeling is that something is getting optimized away at compile time, but I can't seem to get it deparsed like that. Maybe x is really 168x faster than map in this case (and in your perl build and on your machine)..

      Makeshifts last the longest.

        something is getting optimized away at compile time

        Maybe it is due to the fact that Blake's was a real subroutine with parameters and mine is more like a <code>constant<code>...

        I expected a wider difference in my test case. Of course, Blake's is far more general than mine and it's results are much more reliable.

        Ciao!
        --bronto

        # Another Perl edition of a song:
        # The End, by The Beatles
        END {
          $you->take($love) eq $you->made($love) ;
        }