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

查看:20
本文介绍了遍历 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

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

实施 3

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

实施 4

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

实施 5

map { SubRoutine($_) } @Array ;

推荐答案

  • 在速度方面:#1 和 #4,但在大多数情况下不会太多.

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

      您可以编写一个基准来确认,但我怀疑您会发现 #1 和 #4 稍微快一些,因为迭代工作是在 C 而不是 Perl 中完成的,并且不会发生不必要的数组元素复制.($_aliased 到 #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天全站免登陆