Reputation: 1892
What is the best way, during a recursive call, to either get or calculate the available remaining stack memory in Java?
(I'm trying to segment a deep recursive call to use as much of the stack as possible (for the sake of speed performance) but without hitting stack overflow.
I've already done a "heap" version, which carried a speed performance overhead, which is why I'm doing this optimization.)
Upvotes: 5
Views: 384
Reputation: 1643
I'm surprised that the iterative approach is less performant. Generally the recursive approach would be slower due to the overhead of method calls. If your algorithm can be implemented as tail-recursive it almost certainly would be faster as an iterative implementation. Can you tell us more about what you're actually trying to do? Perhaps the difference in performance is more algorithmic than just switching iteration for recursion. Here is an example from some CS lecture notes that references a recursive approach to calculating Fibonacci numbers that is O(2^n) whereas the iterative approach is O(n). I believe (although I haven't tried) it is possible to write a recursive Fibonacci number generator that is O(n).
Edit:
One final thought. IMHO it would be much better to use a slower approach that is free of the problems of stack overflow, than introduce all the complexity of trying to determine that you're about to overflow the stack and have some fallback mechanism to avoid it.
Upvotes: 1
Reputation: 533492
I would write the method to be less recursive. Often there are ways to make less (or no) recursive calls.
If you sum a list recursively, adding the first value to the sum of the rest, this will make calls to a depth of N. However, if you cut the list in half and sum the values. (return the value if only one in the list) the recursive depth is log2(N).
Upvotes: 1
Reputation: 15052
Hmmm. If you're worried, you could always keep a depth counter as part of your recursion.
Upvotes: 1
Reputation: 500297
There is no way to do this in a portable manner.
Not only this is OS-specific, in practice the maximum size of the stack is subject to multiple constraints (ulimit -c
, the amount of available virtual memory, -Xss
and -XX:ThreadStackSize
settings etc). This makes it hard to know which constraint will be hit first, even if you could reliably measure how much stack space has been consumed so far.
Upvotes: 2
Reputation: 3509
What for do you need it? Just curiosity? What is the units of measure - bytes or number of recursive invocations?
You can always make infinite recursive call, catch StackOverflowError
and count stack frames
Upvotes: 1