recursion and static methods

Hey, fellow developers:)

a short one:)
is it safe to recursively call a static method?

cheers Paul

its save as long as you can prevent a stack overflow…

:-/ well, i’ve just managed to get a stack overflow in my recursively calles BSPTree builder, so i should make the methods non static?!

cheers,

Paul

No. You’re got a stack overflow because you’re not breaking out of your recursive function chain - static has nothing to do with this.

Go back through the code and confirm that your logic is correct.

You might be getting overflows even with correct logic, if your problem is big enough. Recursion is very easy to program, but fantastically inefficient.

Actually I vaguely remember Jeff mentioning that Java’s recursion isn’t all that inefficient. The implication was that it is more efficient that recursion in a typical C program.

It might be more efficient, but you have still only got a finite amount of stack space. (Tail recursion would be a good optimisation for the JVM to do here.)

Making it non static is not going to help any. You will want to use iteration instead.