Proper Tail Recursion is About Space Efficiency
Although proper tail recursion does tend to make programs run faster, proper tail recursion is really about space efficiency: Properly tail recursive implementations of a programming language are asymptotically more space-efficient than implementations that are not properly tail recursive.
That is easy to demonstrate.
;;; Given two non-negative integers, returns their sum. (define (sum m n) (if (= m 0) n (sum (- m 1) (+ n 1))))
In Scheme,
(sum 1000000 1)
runs in constant space and
returns 1000001.
Implementations of Java are not properly tail recursive,
and seldom attempt tail call optimization,
so giving m
and n
as inputs to
the following method takes Θ(m) stack space.
With m = 1000000, you'll probably get a stack overflow.
// Given two non-negative integers, returns their sum. static int sum (int m, int n) { if (m == 0) return n; else return sum (m - 1, n + 1); }