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

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.

Replies are listed 'Best First'.
Re^11: How to speed up a nested loop?
by Xenofur (Monk) on Sep 21, 2008 at 09:39 UTC
    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.