Prove that using a range operator in a loop does not use additional memory

后端 未结 3 1165
野的像风
野的像风 2021-01-02 11:08

The current documentation for the Range operator .. states that it will not burn up memory for counting loops:

... The range operator is useful for wr

3条回答
  •  悲&欢浪女
    2021-01-02 11:50

    Is there a way that one could go about proving that a counting loop does not waste memory?

    One way might be to monitor the process with top. For example:

    perl -E 'for( 1 .. 1_000_000_000_000 ) { say $_ }' > /tmp/blah & top -pid $!
    

    This shows that the memory usage remains fairly constant (and trivial) while the program runs, despite iterating a list of one trillion items.

    Does anyone know which versions of Perl had the memory issue and when it was fixed?

    I couldn't find the precise version when this was changed with a quick grep of the perldeltas. I will note that perlop mentions it:

    The range operator is useful for writing "foreach (1..10)" loops and for doing
    slice operations on arrays. In the current implementation, no temporary
    array is created when the range operator is used as the expression in
    "foreach" loops, but older versions of Perl might burn a lot of memory
    when you write something like this:
    
        for (1 .. 1_000_000) {
            # code
        }
    

    But it doesn't say when that optimization was introduced. In any case, it was a long time ago.

提交回复
热议问题