in reply to Re: Summing Up Array Elements By Group
in thread Summing Up Array Elements By Group

Even faster:
tin4=> sub { my $b = 0; $output[$_] = $arr[$b++] + $arr[$b++] + $arr[$b++] for 0..@arr/3; }, tin5=> sub { my $b = -1; $output[$_] = $arr[++$b] + $arr[++$b] + $arr[++$b] for 0..@arr/3; },
Rate tin1 tin2 tin3 tin4 tin5 tin1 10.2/s -- -54% -59% -65% -68% tin2 22.2/s 118% -- -9% -23% -30% tin3 24.5/s 141% 10% -- -15% -23% tin4 28.8/s 183% 30% 17% -- -9% tin5 31.7/s 211% 43% 29% 10% --

Replies are listed 'Best First'.
Re^3: Summing Up Array Elements By Group
by hbm (Hermit) on Jan 21, 2009 at 18:34 UTC
    ikegami, this one knocks me down! Did you know in advance that ++$b would be faster than $b++? Do you know why that is?

      $b++ makes a copy so that it can return the previous value. ++$b does not need to.

      I have run into this issue before in C++, but it was normally not a problem for integers. Scalars on the other hand are a different beast.

      G. Wade

        it was normally not a problem for integers.

        I find it odd that it would matter at all for ints.

        ++a --- inc a mov a, reg a++ --- mov a, reg inc a

      $b++ needs to create a new anonymous scalar because the result is different than the $b.

      ++$b just returns a pointer to $b.

      $ perl -le'my $b = 4; $r = \( $b++ ); $$r = 20; print $b' 5 $ perl -le'my $b = 4; $r = \( ++$b ); $$r = 20; print $b' 20
        Nice! One point for your original and another for gwadej's explanation.