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)
StringBuffer.bbelow the last line of your code, the optimizer has enough information to let the environment garbage-collectbas soon as it’s done withtoStringThe fact that there is no variable for
bdoes not make the object created bynewless real. The compiler will probably optimize both snippets into identical bytecode, too.