CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Mar 2002
    Location
    Miami, Fl, US, North America, America, Earth
    Posts
    60

    Recursion vs Loop

    Hi.
    Recursion is slower than loops due to stacks and that stuff. However, I'm wondering if good compilers (VC++, gcc...) change some types of recursion into loops during optimization.
    For example,
    void demo(int i){
    if (i==0) do something;
    demo(i-1);
    }
    Since the call to the function is the last line, there's no need to save it into the stack. Ex: SML optimizes it this way. I'm wondering about C++.
    Thanks

  2. #2
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    2,236
    I doubt it, but you could compile that code an look at the assembly. Every C++ compiler is different, so I can't say what "C++" will do. Some compilers may optimize in a certain way, but not all will.

  3. #3
    Join Date
    Mar 2002
    Location
    Miami, Fl, US, North America, America, Earth
    Posts
    60
    Thx for your reply.
    Yes I tried it and saw the disassembly window in VC++. It translates it into a loop in VC++ .NET in release mode (but not in debug mode).

  4. #4
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    2,236
    No optimizations are made in debug mode. Otherwise when steping through your program it wouldn't go where/do what you expect.

  5. #5
    Join Date
    May 2001
    Location
    United States
    Posts
    725
    Well, to test a compiler out, you could simply write a highly inefficient recursive function and then an iterative function that accomplishes the same task. Use both of them and see which one runs more quickly. If there is a large difference in run-time, then no optimization must have been made.

    Fierytycoon

  6. #6
    Join Date
    Aug 2002
    Posts
    58
    I know for certain that many compilers will optimize tail recursion into an iterative solution.

    (Briefly) Tail recursion means that there are no operations after the recursive call - and that kind of recursion is really easily translated into a loop.

    Regards,
    Bassman

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured