【发布时间】:2023-09-10 04:22:01
【问题描述】:
我在向一位朋友解释说,我希望 Scala 中的非尾递归函数比尾递归函数慢,所以我决定验证一下。 我以两种方式编写了一个很好的旧阶乘函数并尝试比较结果。代码如下:
def main(args: Array[String]): Unit = {
val N = 2000 // not too much or else *s
var spent1: Long = 0
var spent2: Long = 0
for ( i <- 1 to 100 ) { // repeat to average the results
val t0 = System.nanoTime
factorial(N)
val t1 = System.nanoTime
tailRecFact(N)
val t2 = System.nanoTime
spent1 += t1 - t0
spent2 += t2 - t1
}
println(spent1/1000000f) // get milliseconds
println(spent2/1000000f)
}
@tailrec
def tailRecFact(n: BigInt, s: BigInt = 1): BigInt = if (n == 1) s else tailRecFact(n - 1, s * n)
def factorial(n: BigInt): BigInt = if (n == 1) 1 else n * factorial(n - 1)
结果让我很困惑,我得到这样的输出:
578.2985
870.22125
意思是非尾递归函数比尾递归函数快30%,而且运算次数是一样的!
如何解释这些结果?
【问题讨论】:
标签: scala tail-recursion