简体   繁体   中英

Which is more efficient recursion or loops?

I am curious which is more efficient for iteration. I am using one to break up a parse a string into a List. Is recursion more CPU efficient or is looping? Is either more memory efficient? By looping, I am referring to for, for each, do while, while, and any other types. Out of these loops which are more efficient? Or are they all equally? Just curious.

You can't make a general statement on that. It depends on what the loop is doing, how you have coded it ... and how well the JIT compiler is able to optimize it. It can also make a difference what kind of list the loop is iterating over. The same goes for recursion.

To get a reliable answer, you need to examine the various alternatives on a case-by-case basis, and (carefully!) benchmark the specific examples on your Java platfrom.

Recursion in Java has the problem that each level of recursion requires a stack frame, and Java stacks have bounded size. If you have to recurse too deeply, your algorithm will crash with a StackOverflowError . (Current generation Java platforms do not implement tail call optimization.)

You also want to avoid doing index-based iteration (eg for i = 0 to size - 1 ) over a LinkedList , because that will give you O(N^2) behaviour.


Fortunately, the difference in performance for the different kinds of Java loop usually doesn't make enough difference to matter. So (modulo the stack depth issue, and the issue of choosing the correct List class), you can safely leave performance to "later" ... and deal with it if-and-only-if it becomes necessary to do performance optimization.

Iteration is generally going to be more efficient. Recursion requires more memory (to set up stack frames) and time (for the same). However, if you can set up tail recursion, the compiler will almost certainly compile it into iteration, or into something which is similar, giving you the readability advantage of recursion, with the performance of an iterative method.

In some situations an iterative solution will be implemented by essentially maintaining your own stack, so the difference may be minimal.

See Is recursion ever faster than looping? for more details.

Well according to me, the best answer to your question would be "it depends" :

On average, recursion is much faster when searching through a SORTED collection because you can use algorithms like "Divide and Conquer" (in this case cutting the collection in two parts and sending the half where the element could be to the next step of the recursion. The recursion stops when the element is either found, or not contained in the collection).

For most cases though, loops are more efficient than recursion for the simple fact that while going down in the different levels of recursion, the CPU keeps variables in the stack, which basically fills it up. Loops only use a constant amount of room in the stack (generally, but exceptions apply). For example, if you were the calculate the Fibbonacci sequence with a recursive algorithm, it would take you years to get a result after Fibonnacci(30). That sequence can be calculated with the Memoization (basically using loops).

One thing to remember is that recursion is easier to understand and helps resolve problems much more easily than loops. Lots of loop based solutions to problems start with a recursive algorithm (Divide and Conquer) that gets optimised in a loop algorithm (Memoization). I took a class on this subject and it was really interesting.

Hope I helped.

Regards.

certain circumstances are better for recursion...and others for simple iteration. navigating directories for example is superior with recursion. Same for other tree structures. However recursion uses more memory. For iterating a simple list (like a string) iteration (loops) is more efficient.

In my option, Looping is better, recursion will have the function call trace, which will occupy more memory. And again its depends on the functionality

I agree with the other posters in that it really depends on what problem you are solving. My personal preference is to usually avoid recursion as it can be harder to maintain and possibly debug compared to iteration and depending on the skill of the implementor or maintainer, (whover is the weaker link). One item not mentioned however is that with some of the new Java threading feature (eg the ForkJoinPool) a recursive solution can very easily be made into a multi-threaded one. Not that threading in Java is difficult, but it is something to consider while designing a system if distributing the workload in threads becomes an issue and this type of feature is useful.

I have created two microbenchmarks which measure recursion vs loop performance. Both of them perform calculations over a randomized dataset to avoid JIT cheating.

In the first case I calculate a sum of the cells in a randomized integer matrix. With a side of a matrix equal to 60 recursion is 10x slower than loops.

In the second case I compare recursion vs recursion emulation by generating Fibonacci numbers. Recursion emulation is GC-friendly - there are no memory allocations during computation. In this case recursion was 2x faster in 'smaller' cases and 5x faster under a heavy computation.

So the bottom line is that recursion in Java is very effective, though not effective as loops.

Environment:
OS: Windows 8 6.2, Core i5
JVM: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 23.25-b01

Source available at github .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM