简体   繁体   中英

Perl performance: for(1..200000) vs for($_=1;$_<=200000;$_++)

for(1..200000) {...} vs for($_=1;$_<=200000;$_++) {...}

Does the first one have to create an array of 200,000 items or is it just about the same as the second?

I can definitively say that for with a range ( $lower .. $upper ) doesn't create an actual temporary list in memory. It did 12 years ago, but not anymore. And as a matter of fact, it gives better performance than the explicit C-style for-loop (as others' benchmarks have shown), because Perl is able to do the counting loop in nice, efficient internal code. You shouldn't be afraid to use it.

$ time perl -e '$a=0;for(1..10000000){$a++;}'

real 0m0.523s
user 0m0.520s
sys  0m0.000s

$ time perl -e '$a=0;for($_=1;$_<=10000000;$_++){$a++;}'

real    0m1.309s
user    0m1.300s
sys  0m0.000s

So the former is faster, which suggests the answer to your question is a no. It is very likely optimised as for i in xrange(n) is in Python.

I'm curious if it's because you're incrementing both $_ and $a in the second, whereas the first performs an internal increment.

  • time perl -e 'for($_=1;$_<=10000000;){$_++;}'

     real 0m0.544s user 0m0.540s sys 0m0.000s 
  • time perl -e 'for($_=1;$_<=10000000;$_++){$a;}'

     real 0m0.593s user 0m0.580s sys 0m0.000s 

    both get rid of the additional variable and also have closer results, but they are not equivalent to the original example


Like JavaScript, a reverse while loop would be even faster than your second method, and slightly slower than your first:

  • time perl -e '$a=0;for($_=10000000;$_--;){$a++;}'

     real 0m0.543s user 0m0.530s sys 0m0.000s 
  • time perl -e '$a=0;$_=10000000;while($_--){$a++;}'

     real 0m0.569s user 0m0.550s sys 0m0.010s 

    both are equivalent to the original example; however it may not be usable if you can't step backward. they are closer to your first one's results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM