http://qs321.pair.com?node_id=172218


in reply to Re: map, grep, for, foreach
in thread map, grep, for, foreach

As far as I can tell for and foreach are not the same. The do the have the same functionality but due to the internals of perl they execute differently (something to do with lookup tables I believe, but not sure :P ).

A foreach runs far faster than for.

I converted one of my data mangling scripts to foreach loops and the whole thing sped up 35%. Ever since I have stopped believing what they say about for and foreach being the same and only ever use foreach if there is a choice between the two.

Replies are listed 'Best First'.
Re: Just a quick note...
by Elian (Parson) on Jun 06, 2002 at 18:04 UTC
    I'm interested in how you managed to draw that particular conclusion, since:
    for (1..3) {}
    and
    foreach (1..3) {}
    compile to the identical same optree.
Re: Just a quick note...
by jsprat (Curate) on Jun 06, 2002 at 18:25 UTC
    C:\>perl -MO=Deparse -e "print for (1..10);print foreach (1..10);" foreach $_ (1 .. 10) { print $_; } foreach $_ (1 .. 10) { print $_; } -e syntax OK

    OK, I'm confused. They parse identically.

    Do you mean 'C-style' for loops (for (i=1;i++;i<11))vs 'perl-style' for loops? If so, what you describe is documented in perlsyn.

    If not, what do you mean?

Re: Just a quick note...
by runrig (Abbot) on Jun 06, 2002 at 17:39 UTC
    A foreach runs far faster than for.

    Please post a small sample of code demonstrating this phenomenon.