5,533,615 members and growing! (17,334 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » General     Intermediate License: The Code Project Open License (CPOL)

Iterative vs. Recursive approaches

By Eyal Lantzman

Implication of not thinking of iterative solutions over recursive from performance (response time) point of view.
C# 2.0, C# 3.0, C#, Windows, .NET, .NET 3.5, .NET 3.0, .NET 2.0VS2005, VS2008, Visual Studio, Dev

Posted: 5 Nov 2007
Updated: 5 Nov 2007
Views: 9,512
Bookmarked: 13 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
20 votes for this Article.
Popularity: 4.76 Rating: 3.66 out of 5
2 votes, 10.0%
1
2 votes, 10.0%
2
2 votes, 10.0%
3
5 votes, 25.0%
4
9 votes, 45.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

Originaly posted at blogs.microsoft.co.il/blogs/Eyal

Recursive functions – is a function that partially defined by itself and consists of some simple case with a known answer. Example: Fibonacci number sequence, factorial function, quick sort and more.
Some of the algorithms/functions can be represented in iterative way and some may not.

Iterative functions – are loop based imperative repetition of a process (in contrast to recursion which has more declarative approach).

Comparison between Iterative and Recursive approaches from performance considerations

Factorial:

        //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 11 ticks
100 846 ticks 23 ticks
1000 3368 ticks 110 ticks
10000 9990 ticks 975 ticks
100000 stack overflow 9767 ticks

As we can clearly see the recursive is a lot slower than the iterative (considerably) and limiting (stackoverflow).

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

Fibonacci:

        //--------------- iterative version ---------------------    

        static int FibonacciIterative(int n)
        {
            if (n == 0) return 0;
            if (n == 1) return 1;
 
            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 --------------------- 

        static int FibonacciRecursive(int n)
        {
            if (n == 0) return 0;
            if (n == 1) return 1;
 
            return FibonacciRecursive(n - 1) + 
    FibonacciRecursive(n - 2);
        }

        //--------------- optimized recursive version ---------------------

        static Dictionary resultHistory = 
    new Dictionary();
         
        static int FibonacciRecursiveOpt(int n)
        {
            if (n == 0) return 0;
            if (n == 1) return 1;
            if (resultHistory.ContainsKey(n)) 
    return resultHistory[n];
 

            int result = FibonacciRecursiveOpt(n - 1) + 
    FibonacciRecursiveOpt(n - 2);
            resultHistory[n] = result;

            return result;
        }
N Recursive Recursive opt. Iterative
5 5 ticks 22 ticks 9 ticks
10 36 ticks 49 ticks 10 ticks
20 2315 ticks 61 ticks 10 ticks
30 180254 ticks 65 ticks 10 ticks
100 too long/stack overflow 158 ticks 11 ticks
1000 too long/stack overflow 1470 ticks 27 ticks
10000 too long/stack overflow 13873 ticks 190 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 memoization pattern (saving previous results in dictionary for quick key based access), although this pattern isn't match for iterative approach (but definitely improvement over the simple recursion).

Notes

1. The calculations may be wrong in big numbers, however the algorithms should be 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 not always the best performing when used in "recursive situations".

3. If you required to use recursion at least try to optimize it with dynamic programming approaches (such as memoization)

History

Post: November 06, 2007

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Eyal Lantzman


In the last couple of years I'm working as Microsoft sub contractor in various project types - LOB, applications, CnC applications and Distributed applicaitons all of them considered to be extra large in tems of man power (or brain power), duration and geographic destribution between connected sites.
Occupation: Software Developer (Senior)
Company: Taldor
Location: Israel Israel

Other popular Algorithms & Recipes articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralIt's a question of data structuremembervirtuPIC21:45 15 Nov '07  
Generalblame C#, not .NET. F# does it better.memberJay R. Wren3:00 13 Nov '07  
GeneralRe: blame C#, not .NET. F# does it better.memberncarey8:29 13 Nov '07  
GeneralHummembersmesser6:06 6 Nov '07  
GeneralRe: HummemberEyal Lantzman21:08 6 Nov '07  
GeneralGood Jobmembermerlin9815:24 6 Nov '07  
GeneralGood Best PracticememberThe DevMan1:33 6 Nov '07  
GeneralInterestingmembernorm .net22:46 5 Nov '07  
GeneralRe: InterestingmemberEyal Lantzman23:32 5 Nov '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Nov 2007
Editor:
Copyright 2007 by Eyal Lantzman
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project