Best way to iterate through a Perl array

后端 未结 6 1232
死守一世寂寞
死守一世寂寞 2020-12-23 03:03

Which is the best implementation(in terms of speed and memory usage) for iterating through a Perl array? Is there any better way? (@Array need not be retained).

6条回答
  •  情歌与酒
    2020-12-23 03:20

    1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.

    I'd say #3 is pretty wacky and probably less efficient, so forget that.

    Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:

    undef @Array;
    

    when done.

    • NOTE: The subroutine containing the scope of the array actually keeps the array and re-uses the space next time. Generally, that should be fine (see comments).

提交回复
热议问题