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

Ok, i got the problem now. The difference is that initially the tiles array is undefined, which makes an explicit grab of a reference inside it work different than an implicit.
use Data::Dumper; ###################################### my @multi; my $what_is_this = \$multi[1]; foreach my $i ( 10 .. 12 ) { foreach my $j ( 10 .. 12 ) { $multi[$i-10][$j-10] = "$i,$j"; } } print Dumper $what_is_this; print "\n\n"; ###################################### my @multi2; my $what_is_this2 = $multi2[1]; foreach my $i ( 10 .. 12 ) { foreach my $j ( 10 .. 12 ) { $multi2[$i-10][$j-10] = "$i,$j"; } } print Dumper $what_is_this2; print "\n\n"; ###################################### my @multi3; foreach my $i ( 10 .. 12 ) { foreach my $j ( 10 .. 12 ) { $multi3[$i-10][$j-10] = "$i,$j"; } } my $what_is_this3 = $multi3[1]; print Dumper $what_is_this3; __END__ $VAR1 = \[ '11,10', '11,11', '11,12' ]; $VAR1 = undef; $VAR1 = [ '11,10', '11,11', '11,12' ];
Me thinking $tiles_for_rx getting the size was caused by it being an empty scalar after the assignment, which made sense considering that tiles was at that point still empty.

Replies are listed 'Best First'.
Re^8: How to speed up a nested loop?
by tilly (Archbishop) on Sep 18, 2008 at 23:04 UTC
    Oops, my bad. I didn't know what datastructure you had so I hadn't realized that you were autovivifying there. Make that line:
    my $tiles_for_rx = ($tiles[$rx] ||= []);
    instead and see if it works better.
      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.
        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.