Saturday, March 16, 2013

Tail Call



// Non tail-call optimization
// Because the last statement is n+sum1() in the function call, 
// which triggers the saving of sum1()'s current context, then do the next call
int sum1(int n) {
 return (n <= 0) ? 0 : n+sum1(n-1);
}

// We can skip this step by passing the current sum as an argument in the function
int sum2(int n, int cur) {
 return (n <= 0) ? cur : sum2(n-1, cur+n);
}

The processor time it takes to execute these two functions are (N is the # of repetitions):

   N      sum1      sum2
 1000     1123      1061
10000    13213     12839



Ref.: http://c2.com/cgi/wiki?TailCallOptimization

No comments:

Post a Comment

(Coding && Eating) || Sleeping