首页 > 解决方案 > 哪个功能最快,如何?

问题描述

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

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

标签: scala

解决方案


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

推荐阅读