in reply to Re^3: Lagrange Polynomials in Perl
in thread Lagrange Polynomials in Perl

Yeah, I was thinking of it as the stopping point for the for loop more than the last point, although you are right...it's pretty unclear.

Replies are listed 'Best First'.
Re^5: Lagrange Polynomials in Perl
by BrowserUk (Patriarch) on Apr 29, 2015 at 15:08 UTC

    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.


    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.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
      That is actually much more efficient, thank you. I will use that from now on.