sub depth {
return 0 unless ref $_[0] eq 'ARRAY';
return depth( ${$_[0]}[0] ) + 1;
}
####
sub depth {
my $array = shift;
my $count = 0;
while (ref $array eq 'ARRAY') {
$array = ${$array}[0];
++$count;
}
return $count;
}
####
Benchmark: timing 100000 iterations of loop, recursion...
loop: 6 wallclock secs ( 5.30 usr + 0.00 sys = 5.30 CPU) @ 18867.92/s (n=100000)
recursion: 6 wallclock secs ( 5.87 usr + 0.00 sys = 5.87 CPU) @ 17035.78/s (n=100000)
####
#!/usr/bin/perl
use Benchmark;
use strict;
timethese (100000, {
'recursion' => q!
sub depth {
return 0 unless ref $_[0] eq 'ARRAY';
return depth( ${$_[0]}[0] ) + 1;
};
my $array = [ [ [ 1 ], [ 1 ] ], [ [ 1 ], [ 1 ] ]];
my $result = depth($array);
!,
'loop' => q!
sub depth {
my $array = shift;
my $count = 0;
while (ref $array eq 'ARRAY') {
$array = ${$array}[0];
++$count;
}
return $count;
}
my $array = [ [ [ 1 ], [ 1 ] ], [ [ 1 ], [ 1 ] ]];
my $result = depth($array);
!
});