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

What i don't understand in your code is what the purpose of this is meant to be:
my $tiles_for_rx = $tiles[$rx];
My understanding is that this dumps the size of $tiles[$rx] in $tiles_for_rx, due to being a multi-dimensional array. I may be wrong there, but the debugger seems to agree.

However my understanding or lack of is not the point here. The point is that your variant did not work in the live when applied to my code. This works:
my ($rx,$ry,$y,$x,$xScaled); my $bxScaled = $bx * 16; my $byScaled = $by * 16; my $tile_index=0; my (@realx,@realy); my ($tile); for $x ( 0..15 ) { $rx = $bxScaled+$x; my $tile = \$tiles[$bz][type][$rx]; for $y ( 0..15 ) { $ry = $byScaled+$y; if ( !defined $$tile->[$ry] || $$tile->[$ry] != $type_data[$tile_index] ) { $changed = 1; $$tile->[$ry] = $type_data[$tile_index]; } ++$tile_index; } }
When i try to refactor it to look like your example, it doesn't. Now mind you, i may be making some kind of mistake somewhere, but i'm fairly sure that your variant can't work. Feel free to correct me if i am making a mistake.

Replies are listed 'Best First'.
Re^6: How to speed up a nested loop?
by kyle (Abbot) on Sep 18, 2008 at 16:32 UTC

    I may be wrong there, but the debugger seems to agree.

    I don't see how the debugger can agree with that. Let's set up a multidimensional array and see what happens!

    use Data::Dumper; my @multi; foreach my $i ( 10 .. 12 ) { foreach my $j ( 10 .. 12 ) { $multi[$i-10][$j-10] = "$i,$j"; } } my $what_is_this = $multi[1]; print Dumper $what_is_this; __END__ $VAR1 = [ '11,10', '11,11', '11,12' ];

    The code in question actually gets a reference to an array, which is what's output by Data::Dumper.

    To get the number you're talking about, the syntax would be:

    my $n = scalar @{ $multi[1] };

    The use of scalar is not needed functionally, but it makes it easier to see what's meant.

      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. 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.
        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.