Joe Smith said:
But the scalar operator doesn't return the array size by
iterating over all the values; it returns a field in the variable
that holds the array size.
Both methods should operate at the same speed since they both
look up a variable in the symbol table, then return an int
stored in the struct that describes the variable.
One should think so, but benchmarks show otherwise:
use Benchmark qw( cmpthese);
our @sort_start = qw( 1 2 3 4 5 6 7 8);
our $sizeof_sort_start = @sort_start;
cmpthese -3, {
direct => 'for ( my $i = 0; $i < @sort_start; ++ $i ) { 1 }',
scalar => 'for ( my $i = 0; $i < scalar @sort_start; ++ $i ) { 1 }',
cached => 'for ( my $i = 0; $i < $sizeof_sort_start; ++ $i ) { 1 }',
};
Rate scalar direct cached
scalar 9054/s -- -7% -29%
direct 9736/s 8% -- -24%
cached 12730/s 41% 31% --
Apparently it's not the explicit "scalar" that slows it down (if anything,
it speeds it up a bit), but accessing the array length at all.
The relative speeds don't change much for larger @sort_start.
Anno