sberezin
sberezin

Reputation: 3296

Externalizing local variables in recursive method in Java

I've got a recursive method which has local String variables:

private void recursiveUpdate(int id){
    String selectQuery="Select ...";
    String updateQuery="Update or rollback ..."

    ...

    for(int childID: children)
        recursiveUpdate(childID);
}

Is there any reason to externalize local String variables like this:

private static final String selectQuery="Select ...";
private static final String updateQuery="Update or rollback ..."

private void recursiveUpdate(int id){
    ...

    for(int childID: children)
        recursiveUpdate(childID);
}

Upvotes: 0

Views: 149

Answers (4)

Isaiah van der Elst
Isaiah van der Elst

Reputation: 1445

Typically you should be concerned with the size of your stack memory when making recursive calls. This tells the cpu where to jump when the method completes. It contains your method parameters and returning location.

Object instantiated within the body of the method are saved in the heap. In this case, I think the compiler will figure out that these are constants and save them to static memory. The heap is much larger and is more likely to survive the recursion when objects are instantiated so I wouldn't worry about it.. By moving object out, you'll save a little space in your heap.

IMO, it's best to move the variable out, if the values are always the same (no-dynamic). This way, if they ever change, you can find them easily.

Upvotes: 0

Thomas
Thomas

Reputation: 88707

From a technical point of view the difference between the two should be negligible since in either case you'd always use the same string instances. If you are parsing those query in every call you might consider externalizing that as well (e.g. using prepared statements).

From a development point of view, I'd probably externalize the queries to separate them from the call logic.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

In the former case, you are relying on the compiler to recognize that those strings are unchanging across all calls so it doesn't need to give a fresh copy of each variable to each invocation of recursiveUpdate, whereas in the latter case, there is no question about it.

Upvotes: 1

DanSchneiderNA
DanSchneiderNA

Reputation: 378

Yes. You'd want to externalize the variables. If left as a local variable, amd depending on the size of the call stack, you could quickly accumulate many string objects and lower efficiency. Even worse if making edits to the string inside the recursive method. Also, you will not be making changes to the strings as it appears to me, so if used as a 'reference' it would be better to externalize it.

Upvotes: 0

Related Questions