"Algorithmic" reprint: Iterative vs. Recursive approaches

Source: Internet
Author: User

Iterative vs. Recursive approaches Eyal Lantzman, 5 Nov Cpol

Introduction

This article is originally posted at Blogs.microsoft.co.il/blogs/eyal.

Recursive Function–is a function that's partially defined by itself and consists of the some simple case with a known Answe R. Example:fibonacci number sequence, factorial function, quick sort and more.
Some of the algorithms/functions can is represented in an iterative and Some is not.

Iterative Functions–are loop based imperative repetitions of a process (in contrast to recursion which have a more declar ative approach).

Comparison between iterative and Recursive approaches from performance considerationsfactorialCollapse | Copy Code
//Recursive function calculates n!static int factorialrecursive ( int n) {if (n <= 1) return 1; return n * factorialrecursive (n-1);} //iterative function calculates N! Static int factorialiterative (int N) { int sum = 1; if (n <= 1) return sum; while (n > 1) {sum *= n; n--;} return sum;}             
N Recursive Iterative
10 334 Ticks Ticks
100 846 Ticks Ticks
1000 3368 Ticks Ticks
10000 9990 Ticks 975 Ticks
100000 Stack Overflow 9767 Ticks

As we can clearly see, the recursive are a lot slower than the iterative (considerably) and limiting (StackOverflow).

The reason for the poor performance is heavy push-pop of the registers at the ill level of each recursive call.

FibonacciCollapse | Copy Code
//---------------Iterative version---------------------Staticint Fibonacciiterative (int n) {if (n = =0)Return0;if (n = =1)Return1;int Prevprev =0;int prev =1;int result =0;for (int i =2; I <= N; i++) {result = prev + prevprev; prevprev = prev; prev = result;}return result;}//---------------Naive recursive version---------------------Staticint Fibonaccirecursive (int n) {if (n = =0)Return0;if (n = =1)Return1;Return fibonaccirecursive (N-1) + fibonaccirecursive (N-2);}//---------------Optimized recursive version---------------------Static dictionary<int> resulthistory = new dictionary<int> (); static int fibonaccirecursiveopt ( int N) {if (n = = 0) return 0; if (n = = 1) return 1; if (Resulthistory.containskey (n)) return resultHistory[n]; Span class= "Code-keyword" >int result = Fibonaccirecursiveopt (n-1) + fibonaccirecursiveopt (n -2); Resulthistory[n] = result; return result;}            
N Recursive Recursive opt. Iterative
5 5 Ticks Ticks 9 Ticks
10 Approx. ticks Ticks Ten Ticks
20 2315 Ticks Ticks Ten Ticks
30 180254 Ticks Ticks Ten Ticks
100 Too long/stack Overflow 158 Ticks Ticks
1000 Too long/stack Overflow 1470 Ticks Ticks
10000 Too long/stack Overflow 13873 Ticks Ticks
100000 Too long/stack Overflow Too long/stack Overflow 3952 Ticks

As before, the recursive approach is worse than iterative however, we could apply memorization pattern (saving previous re Sults in dictionary for quick key based access), although this pattern isn ' t a match for the iterative approach (but Defin Itely an improvement to the simple recursion).

Notes
    1. The calculations is wrong in big numbers, however the algorithms should is correct.
    2. For timer calculations, I used System.Diagnostics.Stopwatch .
Points of Interest
    1. Try not to use recursion in system critical locations.
    2. Elegant Solutions is the best performing if used in "recursive situations".
    3. If you required to use recursion, at least try to optimize it with dynamic programming approaches (such as memorization).

Transferred from: http://www.codeproject.com/Articles/21194/Iterative-vs-Recursive-Approaches

About Tail Recursive

It is possible that recursion would be more expensive, depending on if the recursive function is tail recursive is recursive call). Tail recursion should be recognized by the compiler and optimized to their iterative counterpart (while maintaining The concise, clear implementation you has in your code).

I would write the algorithm in the the the-the-makes, the most-sense and are the most clear for the poor sucker (be it yourself or someone else) that have to maintain the code in a few months or years. If you run into performance issues, then profiles your code, and then and only then look into optimizing by moving An iterative implementation. You could want to look into memoization and dynamic programming.

Transferred from: http://stackoverflow.com/questions/72209/recursion-or-iteration

Resources:

Tail Call:

Http://zh.wikipedia.org/wiki/%E5%B0%BE%E8%B0%83%E7%94%A8

Http://en.wikipedia.org/wiki/Tail_call

"Algorithmic" reprint: Iterative vs. Recursive approaches

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.