迭代Perl数组的最佳方法 [英] Best way to iterate through a Perl array

查看:118
本文介绍了迭代Perl数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个是迭代Perl数组的最佳实现(在速度和内存使用方面)?有没有更好的方法? ( @Array 无需保留)。

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).

foreach (@Array)
{
      SubRoutine($_);
}



实施2



Implementation 2

while($Element=shift(@Array))
{
      SubRoutine($Element);
}



实施3



Implementation 3

while(scalar(@Array) !=0)
{
      $Element=shift(@Array);
      SubRoutine($Element);
}



实施4



Implementation 4

for my $i (0 .. $#Array)
{
      SubRoutine($Array[$i]);
}



实施5



Implementation 5

map { SubRoutine($_) } @Array ;


推荐答案


  • In速度方面:#1和#4,但在大多数情况下并不多。

    • In terms of speed: #1 and #4, but not by much in most instances.

      你可以写一个基准来确认,但我怀疑你会发现#1和#4稍微快一些,因为迭代工作是在C而不是Perl完成的,并且不会发生数组元素的不必要的复制。 ( $ _ 别名到#1中的元素,但#2和#3实际上复制来自的标量数组。)

      You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_ is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)

      #5可能类似。

      就内存使用而言:他们'除了#5之外都是一样的。

      In terms memory usage: They're all the same except for #5.

      for(@a)是特殊的,以避免扁平化阵列。循环遍历数组的索引。

      for (@a) is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.

      在可读性方面:#1。

      在灵活性方面:#1 /#4和#5。

      In terms of flexibility: #1/#4 and #5.

      #2不支持错误的元素。 #2和#3具有破坏性。

      #2 does not support elements that are false. #2 and #3 are destructive.

      这篇关于迭代Perl数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆