in reply to lc entire contents of array?

McMahon,
$_ = lc for @array;
This is likely more efficient than map - at least in newer versions of Perl.

Cheers - L~R

Replies are listed 'Best First'.
Re: Re: lc entire contents of array?
by dragonchild (Archbishop) on Mar 30, 2004 at 16:14 UTC
    It will be more effecient because it doesn't allocate a new array, then deallocate the previous array. Aliasing is a good thing. :-)

    That said, I personally think that map is more self-documenting and easier to read. $_ = lc for @array; could really use a comment about aliasing in production code.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

Re: Re: lc entire contents of array?
by Willard B. Trophy (Hermit) on Mar 30, 2004 at 22:06 UTC
    What counts as newer versions? I find that map whups for's sorry ass in benchmarks under 5.8.0 and 5.8.2.

    You will have to excuse me; I'm about to return to my roots as a Fortran programmer, where all that matters is speed ...

    --
    bowling trophy thieves, die!

      What counts as newer versions? I find that map whups for's sorry ass in benchmarks under 5.8.0 and 5.8.2.

      Eh?

      use Benchmark; @a = qw(the quick brown fox jumps over the lazy dog); timethese(1000000, { 'for' => '$_ = lc for @a', 'map' => '@a = map lc, @a', }); $ perl580 /tmp/p Benchmark: timing 1000000 iterations of for, map... for: 20 wallclock secs (19.28 usr + 0.02 sys = 19.30 CPU) @ 51 +813.47/s (n=1000000) map: 47 wallclock secs (47.85 usr + 0.02 sys = 47.87 CPU) @ 20 +889.91/s (n=1000000)
        $ ./dave_the_m.pl Benchmark: timing 1000000 iterations of for, map... for: 2 wallclock secs ( 2.03 usr + 0.00 sys = 2.03 CPU) @ 49 +2610.84/s (n=1000000) map: 1 wallclock secs ( 1.12 usr + 0.00 sys = 1.12 CPU) @ 89 +2857.14/s (n=1000000)

        That was Perl 5.8.0 on a P3-600. I got similar results on a Sparc box with 5.8.2.

        I rather think we might be benchmarking other things than just the map and the for. For instance, lcing an array with 10,000 elements doesn't seem to take appreciably longer than one with 1,000 elements.

        Anyway, wiser monks have already pointed out that legibility should come first. Optimisation is a hardware problem.

        --
        bowling trophy thieves, die!

      Willard B. Trophy,
      I think you assumed by efficient I meant faster. There are all kinds of ways to be efficient. Typically you trade memory for speed. As dragonchild points out, the map creates a temporary list. I say newer versions of Perl because older versions of Perl, it is my understanding, did the same thing in for loops.

      Cheers - L~R