On Wed, 6 May 2015 02:18 am, Cecil Westerhof wrote: > Well, I did not write many tail recursive functions. But what surprised > me was that for large values the ‘tail recursive’ version was more > efficient as the iterative version. And that was with myself > implementing the tail recursion. I expect the code to be more > efficient when the compiler implements the tail recursion.
You cannot know that. Python is not C or Java, and your intuition as to what will be fast and what will be slow will not be accurate in Python. Python has its own fast paths, and slow paths, and they are not the same as C's or Java's. I have been using Python for over 15 years, and I would not want to guess whether a hypothetical compiler-generated tail-recursion-elimination function would be faster or slower than manually unrolling the recursion into a while loop. I am surprised that you find a manually unrolled version with a while loop is faster than an iterative version. I assume the iterative version uses a for-loop. In my experience, a for-loop is faster than a while loop. But perhaps that depends on the exact version and platform. -- Steven -- https://mail.python.org/mailman/listinfo/python-list