Hello,
is
for(1 .. 100) {
print if $_ < 50;
}
more efficient than
for(grep {$_ < 50} (1 .. 100)) {
print;
}
or is Perl able to optimize the latter into the former?
Also, is
$array_ref = [1 .. 10000];
for(@$array_ref) {
print;
}
equivalent (efficiency wise) to
$array_ref = [1 .. 10000];
for($i=0; $_ = $array_ref->[$i] ;$i++) {
print;
}
Thanks for any suggestions.
If anyone knows why the faster version is faster - from the Perl internals point of view, I'd like to know that too.
I would have (naively!) expected the for-grep-if version to be 1.5 times slower than the for-if version : 2 loops vs one.
For the 2nd example, I would have guessed the C style loop would be as fast as the Perl style loop since it looks like something that could be mapped straight to equivalent C code.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.