Recursion or Iteration?

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

    As far as I know, Perl does not optimize tail-recursive calls, but you can fake it.

    sub f{
      my($l,$r) = @_;
    
      if( $l >= $r ){
        return $l;
      } else {
    
        # return f( $l+1, $r );
    
        @_ = ( $l+1, $r );
        goto &f;
    
      }
    }
    

    When first called it will allocate space on the stack. Then it will change its arguments, and restart the subroutine, without adding anything more to the stack. It will therefore pretend that it never called its self, changing it into an iterative process.

    Note that there is no "my @_;" or "local @_;", if you did it would no longer work.

提交回复
热议问题