Por que a recursão da cauda do Scala é mais rápida que o loop whil
Aqui estão duas soluções para o exercício 4.9 no Scala para o impaciente de Cay Horstmann: "Escreva uma função lteqgt (valores: Matriz [Int], v: Int) que retorne um triplo contendo as contagens de valores menores que v, iguais a v, e maior que v. " Um usa recursão de cauda, o outro usa um loop while. Eu pensei que ambos seriam compilados com bytecode semelhante, mas o loop while é mais lento que a recursão da cauda por um fator de quase 2. Isso sugere para mim que meu método while está mal escrit
import scala.annotation.tailrec
import scala.util.Random
object PerformanceTest {
def main(args: Array[String]): Unit = {
val bigArray:Array[Int] = fillArray(new Array[Int](100000000))
println(time(lteqgt(bigArray, 25)))
println(time(lteqgt2(bigArray, 25)))
}
def time[T](block : => T):T = {
val start = System.nanoTime : Double
val result = block
val end = System.nanoTime : Double
println("Time = " + (end - start) / 1000000.0 + " millis")
result
}
@tailrec def fillArray(a:Array[Int], pos:Int=0):Array[Int] = {
if (pos == a.length)
a
else {
a(pos) = Random.nextInt(50)
fillArray(a, pos+1)
}
}
@tailrec def lteqgt(values: Array[Int], v:Int, lt:Int=0, eq:Int=0, gt:Int=0, pos:Int=0):(Int, Int, Int) = {
if (pos == values.length)
(lt, eq, gt)
else
lteqgt(values, v, lt + (if (values(pos) < v) 1 else 0), eq + (if (values(pos) == v) 1 else 0), gt + (if (values(pos) > v) 1 else 0), pos+1)
}
def lteqgt2(values:Array[Int], v:Int):(Int, Int, Int) = {
var lt = 0
var eq = 0
var gt = 0
var pos = 0
val limit = values.length
while (pos < limit) {
if (values(pos) > v)
gt += 1
else if (values(pos) < v)
lt += 1
else
eq += 1
pos += 1
}
(lt, eq, gt)
}
}
Ajuste o tamanho do bigArray de acordo com o tamanho da pilha. Aqui está um exemplo de saída:
Time = 245.110899 millis
(50004367,2003090,47992543)
Time = 465.836894 millis
(50004367,2003090,47992543)
Por que o método while é muito mais lento que o tailrec? Ingenuamente, a versão tailrec parece estar em uma pequena desvantagem, pois sempre deve executar 3 "se" verifica todas as iterações, enquanto a versão while geralmente executa apenas 1 ou 2 testes devido à construção else. (Nota: reverter a ordem em que realizo os dois métodos não afeta o resultado