开发者

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 i开发者_如何学Gos 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜