Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Just a quick note...

by Anonymous Monk
on Jun 06, 2002 at 14:28 UTC ( #172218=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://172218]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2022-12-08 20:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?