Search code examples
language-agnosticmemorymemory-managementrecursionfactorial

How does recursion make the use of run-time memory unpredictable?


Quoting from Code Complete 2,

int Factorial( int number ) {
   if ( number == 1 ) {
      return 1;
   }
   else {
      return number * Factorial( number - 1 );
   }
}

In addition to being slow [1] and making the use of run-time memory unpredictable [2], the recursive version of this routine is harder to understand than the iterative version, which follows:

int Factorial( int number ) {
   int intermediateResult = 1;
   for ( int factor = 2; factor <= number; factor++ ) {
      intermediateResult = intermediateResult * factor;
   }
   return intermediateResult;
}

I think the slow part is because of the unnecessary function call overheads.

But how does recursion make the use of run-time memory unpredictable?

Can't we always predict how much memory would be needed (as we know when the recursion is supposed to end)? I think it would be as unpredictable as the iterative case, but not any more.


Solution

  • Because of the fact recursive methods call them selves repeatedly, the need lots of stack memory. Since the stack is limited, errors will occur if the stack memoy is exceeded.