scala - 哪个功能最快,如何?
问题描述
哪一个在性能方面更快。在这种情况下,视图如何使其更快?
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
解决方案
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)
}
推荐阅读
- android - Android Things console not allowing me to create a build
- python - python numpy`np.take`与二维数组
- sql - 看到 ORA-01858 发现非数字字符?
- python - 将文件上传到 s3 并取回公共 URL
- jsr352 - 在运行期间停止 JSR 批处理应用程序而不抛出异常
- javascript - 使用 java 和 video.js 实现无限视频流
- nginx - Nginx try_files 删除 client_max_body_size 选项
- mysql - 将图像更新到 MySQL 数据库时,无法将“System.Byte []”类型的对象转换为“System.IConvertible”类型
- html - HTML & CSS - 你如何显示
- 和
在同一条线上(彼此相邻)? - reactjs - 当我运行 React Native Expo 应用程序时,键盘覆盖 TextInput 表单