【问题标题】:Which fucntion is the fastest and how? [duplicate]哪个功能最快,如何? [复制]
【发布时间】:2020-03-31 20:15:40
【问题描述】:

哪一个在性能方面更快。在这种情况下,视图如何使其更快?

def f(arr: List[Int]): List[Int] =
  arr.zipWithIndex.filter(_._2 % 2 == 1).map(_._1)

def f(arr: List[Int]): List[Int] =
  arr.view.zipWithIndex.filter { _._2 % 2 != 0 }.map(_._1).toList

def f(arr: List[Int]): List[Int] =
  arr.view.zipWithIndex.collect { case (a, b) if (b % 2 == 0) => a }.toList

【问题讨论】:

  • 从技术上讲,唯一的判断方法是使用与您真正重要的用例类似的用例进行基准测试。但是,从理论上讲,第二个或第三个应该比第一个更快,因为它们是惰性的,因此它们在一次迭代中应用所有转换。 (我会选择第三个,因为我更喜欢 collect 而不是 filter + map,但这只是风格)。 - 注意:最好使用 Iterator 而不是 View,如果您在 2.12 Views 已损坏并且在 2.13 Views 是正确的,但 Iterators 稍快。
  • 如果你需要速度(微优化),你应该使用数组。如果您不想要它,请使用一种最简单的方法。我认为你不应该考虑微优化,特别是在这种情况下。过早的优化是万恶之源。

标签: scala


【解决方案1】:
def f(arr: List[Int]): List[Int] =
  arr.grouped(2).flatMap(_.drop(1)).toList

:)


更认真:

def f(arr: List[Int]): List[Int] = {
  @annotation.tailrec
  def loop(rem: List[Int], res: List[Int]): List[Int] =
    rem match {
      case _::b::tail => loop(tail, b +: res)
      case _ => res.reverse
    }

  loop(arr, Nil)
}

【讨论】:

  • 请为您的答案添加一些解释。毕竟,我看不出你是如何回答“这三个函数中哪个函数最快”的问题
猜你喜欢
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多