in reply to Re^8: How to speed up a nested loop?
in thread How to speed up a nested loop?

Wow, thanks! This actually gave a little performance boost.

I guess this is caused by reducing the double-resolution of "$$tile->[]" to a single resolution of "$tile->[]" that this allows.

Replies are listed 'Best First'.
Re^10: How to speed up a nested loop?
by tilly (Archbishop) on Sep 19, 2008 at 18:51 UTC
    Nope. It is caused by factoring yet another lookup out of the inner loop.

    In languages like C this kind of optimization is meaningless because the compiler is smart enough to know when to do it for you. But Perl has to make a trade-off between compiling well and runtime performance, so doesn't make this trade-off.

    If Perl had a JIT compiler then this would go away as well. The Parrot folks have promised a JIT compiler for Perl 6, but I've stopped holding my breath on waiting for that to happen.

      Umm, the look-up was already factored out, only with a different syntax, ie.
      $stuff = \$stuff2[2]; loop { $moo = $$stuff->[3]; }
      instead of
      $stuff = $stuff2[2] || []; loop { $moo = $stuff->[3]; }
      Or i'm misunderstanding something here. :)
        I think you're misunderstanding. What you had before calculated $rx in the loop, and then had:
        ...$tiles[$rx][$ry]...
        in the inner loop. Which looks up index $rx, gets an array reference, looks up index $ry, etc.

        I moved calculating $rx out of the loop and the lookup on $rx out of the loop with:

        my $tiles_for_rx = ($tiles[$rx] ||= []);
        and then in the loop had:
        ...$tiles_for_rx->[$ry]...
        which means that the lookup of index $rx doesn't happen in the inner loop any more.

        If your inner loop executes 15 times for each iteration of the outer loop, you just lost 14 calculations of $rx, and 14 lookups on index $rx. Less work is generally faster.