Skip to main content

Local variables

2 replies [Last post]
Joined: 2007-06-11
Points: 0

Dumb question,

Which code is better in terms of performance, object allocation and memory management?


String a = "";
String b = "";
String c = "";

int n = 1000;

for(i=0; i

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-01-07
Points: 0

Well its pretty much all the same - by the way the space for the references is allocated on the stack as soon as you enter the method.

The question is what you do with the string-objects, if you do a lot of concatenations using the + operator or many calls to methods which return new string-objects (like substring, ...) this will be slow. For concatenation StringBuilder is a good point to start...

Conclusion: Don't worry about the local variables, object creation for the strings will be visible way before ;)

lg Clemens

Joined: 2007-05-28
Points: 0

but one is on the heap and one is on the stack, right? The first one is on the heap, the other is on the stack.. so the second one is best in terms of overall runtime memory footprint?

I took it as implicit that the first one has class scope on the Strings (they're members) and the second on has local scope for the strings (they're declared in a method).