As a test for one of my classes, our teacher asked us to test a recursive and non-recursive approach to the famous Euclidean Algorithm:
Iterative
(defun gcdi (a b) (let ((x a) (y b) r) (while (not (zerop y)) (setq r (mod x y) x y y r)) x)) Recursive
(defun gcdr (a b) (if (zerop b) a (gcdr b (mod a b)))) And then I ran a test:
(defun test-iterative () (setq start (float-time)) (loop for x from 1 to 100000 do (gcdi 14472334024676221 8944394323791464)) ; Fibonacci Numbers close to 2^64 >:) (- (float-time) start)) (defun test-recursive () (setq start (float-time)) (loop for x from 1 to 100000 do (gcdr 14472334024676221 8944394323791464)) ; Fibonacci Numbers close to 2^64 >:) (- (float-time) start)) And then I ran the timers:
(test-recursive) : 1.359128475189209
(test-iterative) : 1.7059495449066162
So my question is this, why did the recursive test perform faster than the iterative test? Isn't iterative almost always better than recursion? Is elisp an exception to this?