in reply to Re^4: Lagrange Polynomials in Perl
in thread Lagrange Polynomials in Perl
In general, if I need to use C-style for loops to traverse arrays, I simply put the @array limit directly in the condition:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Lagrange Polynomials in Perl
by Mascasc (Novice) on Apr 29, 2015 at 15:42 UTC |