Perl: Why is it slower to declare (my) variables inside a loop?

后端 未结 5 1350
余生分开走
余生分开走 2021-01-12 20:58

What\'s the difference, from the interpreter\'s POV, between the following the following programs:

#!/usr/bin/perl -w

use strict;

for (1..10000000) {
    m         


        
5条回答
  •  迷失自我
    2021-01-12 21:34

    Since the example programs you have given do not really do anything it is hard to give you a specific reason why one type of declaration would be better than the other. As many other posters have pointed out, declaring the variable in the loop creates a new variable each time. In your examples that creation is redundant, but consider the following examples using closures.

    my @closures;
    my $jimmy;
    
    for (1 .. 10) {
        $jimmy = $_** 2;
        push @closures, sub {print "$jimmy\n"};
    }
    

    and this one:

    my @closures;
    
    for (1 .. 10) {
        my $jimmy = $_** 2;
        push @closures, sub {print "$jimmy\n"};
    }
    

    In each case the code builds up a series of code references, but in the first example since all the code refs refer to the same $jimmy each one will print 100 when called. In the second example each code ref will print a different number (1, 4, 9, 16, 25, ...)

    So in this case the time difference does not really matter since the two blocks of code do very different things.

提交回复
热议问题