Recursion or Iteration?

前端 未结 30 2415
小鲜肉
小鲜肉 2020-11-22 14:44

Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palind

30条回答
  •  孤城傲影
    2020-11-22 15:34

    it depends on "recursion depth". it depends on how much the function call overhead will influence the total execution time.

    For example, calculating the classical factorial in a recursive way is very inefficient due to: - risk of data overflowing - risk of stack overflowing - function call overhead occupy 80% of execution time

    while developing a min-max algorithm for position analysis in the game of chess that will analyze subsequent N moves can be implemented in recursion over the "analysis depth" (as I'm doing ^_^)

提交回复
热议问题