const val MAX_VALUE = Int.MAX_VALUE
fun calculateFixedPointCosine(after: Int = 1) : Int {
return if(after >= MAX_VALUE - 5) after
else {
calculateFixedPointCosine(after + 1)
}
}
tailrec fun tailRecCalculateFixedPointCosine(after: Int = 1) : Int {
return if(after >= MAX_VALUE - 5) after
else tailRecCalculateFixedPointCosine(after + 1)
}
fun main(args: Array<String>) {
val startWithoutTailRec = System.currentTimeMillis()
val withoutTailRec = calculateFixedPointCosine(1)
val endWithoutTailRec = System.currentTimeMillis()
val startWithTailRec = System.currentTimeMillis()
val withTailRec = tailRecCalculateFixedPointCosine(1)
val endWithTailRec = System.currentTimeMillis()
println("Time Elapsed without tail rec: ${endWithoutTailRec - startWithoutTailRec}, value: $withoutTailRec")
println("Time Elapsed with tail rec: ${endWithTailRec - startWithTailRec}, value: $withTailRec")
}
Now run this code and most probably you will encounter a StackOverflowException
.
Now comment out the code for without tailrec
method calls, and it will run successfully. Which implies that tailrec
has modified your recursion.
Now as the question states that why the compiler is not optimizing it anyway?
The compiler does optimization but that is not guaranteed. meaning that it will not happen always. If the compiler sees fit, it will optimize and some time it wouldn't.
In case you want to enforce this optimization, guaranteed, use tailrec
keyword.