Well I saw tons of answers and even accepted answer but never saw the correct one and was thinking why...
Long story short :
Always avoid recursions if you can make same unit to be produced by loops!
How does recursion work?
• The Frame in Stack Memory is being allocated for a single function call
• The Frame contains reference to the actual method
• If method has objects, the objects are being put into Heap memory and Frame will contain reference to that objects in Heap memory.
•These steps are being done for each single method call!
Risks :
• StackOverFlow when the stack has no memory to put new recursive methods.
• OutOfMemory when the Heap has no memory to put recursive stored objects.
How Does loop work?
• All the steps before, except that the execution of repeatedly code inside the loop will not consume any further data if already consumed.
Risks :
• Single risk is inside while loop when your condition will just never exist...
Well that won't cause any crashes or anything else, it just won't quit the loop if you naively do while(true)
:)
Test:
Do next in your software:
private Integer someFunction(){
return someFunction();
}
You will get StackOverFlow
exception in a second and maybe OutOfMemory
too
Do second:
while(true){
}
The software will just freeze and no crash will happen:
Last but not least - for
loops :
Always go with for
loops because this or that way this loop somewhat forces you to give the breaking point beyond which the loop won't go, surely you can be super angry and just find a way to make for
loop never stop but I advice you to always use loops instead of recursion in sake of memory management and better productivity for your software which is a huge issue now days.
References:
Stack-Based memory allocation