Recursion or Iteration?

前端 未结 30 2596
小鲜肉
小鲜肉 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:16

    Recursion is very useful is some situations. For example consider the code for finding the factorial

    int factorial ( int input )
    {
      int x, fact = 1;
      for ( x = input; x > 1; x--)
         fact *= x;
      return fact;
    }
    

    Now consider it by using the recursive function

    int factorial ( int input )
    {
      if (input == 0)
      {
         return 1;
      }
      return input * factorial(input - 1);
    }
    

    By observing these two, we can see that recursion is easy to understand. But if it is not used with care it can be so much error prone too. Suppose if we miss if (input == 0), then the code will be executed for some time and ends with usually a stack overflow.

提交回复
热议问题