我在向朋友解释我期望Scala中的非尾递归函数比尾递归函数慢,所以我决定验证它.我用两种方式编写了一个很好的旧因子函数,并试图比较结果.这是代码:
def main(args: Array[String]): Unit = {
val N = 2000 // not too much or else stackoverflows
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 …Run Code Online (Sandbox Code Playgroud)