Does perl support foreach optimization in a range?

Given a simple program:

use strict;
use warnings;

my $count = 0;

foreach ('a' .. 'zzzzzzzzzz') {
    $count++;
}

print "$count\n";

Will it perlcreate the entire range around the 1.4+e14elements in memory, and then iterate over them or have any internal optimizations to just go to one state of the range operator at a time?

Well, I actually ran this, so the empirical data from topshow that this is the last (and he has not finished seeing the data from time), but is it documented somewhere or where to find confirmation in the sources?

+4
source share
2 answers

From perldoc perlop :

, foreach, Perl , - [, ]

+7

, :

 for (EXPRX..EXPRY) { ... }

perlop .

, foreach, [ Perl 5.6] , - :

for (1 .. 1_000_000) {
    # code
}

, :

$ perl -e'
   my $n = 10_000_000;
   system("ps h -o rss $$");
   for (1..$n) { system("ps h -o rss $$"); last; }
'
1876
1944

1944 KiB. , , , 10 000 000 . , 385 MiB, :

$ perl -e'
   my $n = 10_000_000;
   system("ps h -o rss $$");
   for ((), 1..$n) { system("ps h -o rss $$"); last; }
'
 1876
394724

10 .

EXPR..EXPR, . -:

  • for (EXPR; EXPR; EXPR) ( "C- ", while.)
    .
  • for (EXPRX..EXPRY) ( .)
    .
  • for (reverse CONSTX..CONSTY) ( , .)
    , . [1]
  • for (reverse EXPRX..EXPRY) ( , .)
    .
  • for (@ARRAY) ( .)
    .
  • for (reverse @ARRAY) ( .)
    .
  • for (reverse LIST) ( , .)
    .
  • for (LIST) ( , .)
    .

  • , for (CONSTX..CONSTY),

    CONSTX..CONSTY
    

    my @anon;
    BEGIN { @anon = CONSTX..CONSTY; }
    @anon
    

    :

    $ perl -e'
       BEGIN { system("ps h -o rss $$"); }
       system("ps h -o rss $$");
       exit(0);
       for (reverse 1..10_000_000) {  }
    '
     1868
    709540
    
+5

Source: https://habr.com/ru/post/1682934/


All Articles