performance - 在 Scala for 循环中倒计时

标签 performance scala scala-2.9 reasoning

这个问题在这里已经有了答案:




9年前关闭。




Possible Duplicate:
Decreasing for loop in Scala?



在工作时 Scala For The Impatient ,我想到了以下练习:
Write a Scala equivalent for the Java loop
       for (int i = 10; i >= 0; i--) System.out.println(i);

It did not take me long to come up with the following solution:

   for (i <- 1 to 10 reverse) {
       println(i)
   }

然而,这让我想知道如何推断这样做的成本。 reverse 方法是对 Range 进行 O(n) 遍历,还是用一些做花哨的索引算术的东西来装饰它?是否有其他结构可以做得更好?

最佳答案

您总是可以选择步骤:

for (i <- 10 to 1 by -1) {
       println(i)
}

根据您关于复杂性的问题。您也可以使用 reversed ,导致覆盖新范围 will be created以相反的顺序(它是 O(1) 操作):
final override def reverse: Range =
    if (length > 0) new Range.Inclusive(last, start, -step)
    else this

这是相当恒定的

关于performance - 在 Scala for 循环中倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499671/

相关文章:

performance - sqlite.fetchall() 慢是正常的吗?

c - 在c中排序双向链表

scala - 为什么 Scala 为 Short 和 Byte 类型定义了一个 "+="运算符?

python - Spark- 计算一列在另一列之后的百分比

Scala-当外部进程退出时获取回调

scala - 如何替换 Scala 2.9 并行集合的 fork 连接池?

scala - 什么是与 Scala 一起使用的最简单的 2D 游戏库?

android - 在 AsyncTask onPostExecute 中使用 canvas.drawBitmap

android - 使用 ByteBuffer 中的像素数据连续更新 SurfaceView 时性能较差

dataframe - Spark Scala 中减去两个数据帧中的列以获得差异