Is tail recursion supported by Numba? I.e., do I have to rewrite recursive functions in a loop style to get the best performance?
Interesting question! Below are code and timings via Jupyter %timeit
to examine. The code is straight from Tail Recursion - GeeksforGeeks.
Tail Recursive Factorial
from numba import njit
@njit
def fact_tailrecursive(n, a = 1):
if (n == 0):
return a
return fact_tailrecursive(n - 1, n * a)
232 ns ± 3.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Loop Factorial
@njit
def fact_loop(n):
a = 1
for i in range(n):
a *= (i + 1)
return(a)
157 ns ± 0.996 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Inbuilt Factorial (Gamma)
import math
@njit
def fact_gamma(n):
return math.gamma(n + 1)
169 ns ± 0.644 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Hopefully that answers your question.