On the problem of using Recursion in algorithms

although the use of recursive algorithm is programmatically readable, it has many problems:

  1. as the computing scale increases, it may cause the call stack to overflow
  2. each function call has time and space overhead. The performance is not very good
  3. is not easy to test, the code is correct when the scale is small, and it is not guaranteed to be correct when the scale is large.

question: should we try to avoid using recursion when writing code and use equivalent loops instead?

Thank you!

Mar.25,2021

"tail recursion" can see that it has the advantage of recursion without worrying about stack overflow.


how to be elegant


this depends on the specific situation. If there is a stable non-recursive algorithm, it is recommended to use it.
but some problems are basically non-recursive and too difficult to deal with.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37a9b-4d74d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37a9b-4d74d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?