Reputation: 30276
For example, you want to reverse a string, will there two ways:
first:
String a = "StackOverFlow";
a = new StringBuffer(a).reverse().toString();
and second is:
String a = "StackOverFlow";
StringBuffer b = new StringBuffer(a);
a = b.reverse().toString();
at above code, I have two question:
1) in first code, does java create a "dummy object" StringBuffer
in memory before do reverse
and change to String
.
2) at above code, does first will more optimize than second because It makes GC works more effectively ? (this is a main question I want to ask)
Upvotes: 1
Views: 123
Reputation: 726499
StringBuffer
.b
below the last line of your code, the optimizer has enough information to let the environment garbage-collect b
as soon as it's done with toString
The fact that there is no variable for b
does not make the object created by new
less real. The compiler will probably optimize both snippets into identical bytecode, too.
Upvotes: 1
Reputation: 2491
In answer to your first question, yes, Java will create a StringBuffer object. It works pretty much the way you think it does.
To your second question, I'm pretty sure that the Java compiler will take care of that for you. The compiler is not without its faults but I think in a simple example like this it will optimize the byte code.
Just a tip though, in Java Strings are immutable. This means they cannot be changed. So when you assign a new value to a String Java will carve out a piece of memory, put the new String value in it, and redirect the variable to the new memory space. After that the garbage collector should come by and clear out the old string.
Upvotes: 0
Reputation: 1500145
Both snippets will create the same number of objects. The only difference is the number of local variables. This probably won't even change how many values are on the stack etc - it's just that in the case of the second version, there's a name for one of the stack slots (b
).
It's very important that you differentiate between objects and variables. It's also important to write the most readable code you can first, rather than trying to micro-optimize. Once you've got clear, working code you should measure to see whether it's fast enough to meet your requirements. If it isn't, you should profile it to work out where you can make changes most effectively, and optimize that section, then remeasure, etc.
Upvotes: 5
Reputation: 3025
StringBuffer b
is not a dummy object, is a reference; basically just a pointer, that resides in the stack and is very small memory-wise. So not only it makes no difference in performance (GC has nothing to do with this example), but the Java compiler will probably remove it altogether (unless it's used in other places in the code).
Upvotes: 1