for( my $i = 0; $i < @array; ++i ) {
...;
}
I realise that you were probably thinking that as you have two nested loops running to the same limit, it might be more efficient to do the size 'calculation' before both and use a scalar; but the reality is that there is no calculation being done, the size of the array represented by @array is simply a direct reference to an internal integer, so the cost is actually less than referencing the integer value of a scalar variable.
The difference isn't big enough to worry about for most purposes: cmpthese -1,{
a=>q[
my @a = 1 .. 1e3;
for( my $i = 0; $i < @a; ++$i ){
for( my$j = 0; $j < @a; ++$j ){
1;
}
}
],
b=>q[
my @a = 1 .. 1e3;
my $l = @a;
for( my $i = 0; $i < $l; ++$i ){
for( my $j = 0; $j < $l; ++$j ){
1;
}
}
]
};;
Rate a b
a 5.81/s -- -41%
b 9.84/s 69% --
[0] Perl>
But the point is that there is little purpose in assigning the size of an array to a scalar variable, just reference it directly when you need it.
Ditto for the length of a perl string.
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
|