I have a feeling that using the: StringBuilder.toString() is slow and very resource-consuming..
So I’m thinking about something like this:
public static void doSomething(String data){ ... }
public static void main(String[] args)
{
StringBuilder s = new StringBuilder();
doSomething(""+s);
}
But I want to know if there is an other “better and fast” way than this, because doSomething(""+s) in a loop will make a new instance of String because of the empty quotes “” I think, and it’s not a good idea to put this inside a loop.
doSomething(""+s);gets translated to the following code by the JVMdoSomething( new StringBuilder().append("").append(s.toString() ).toString() );So now, instead of having 1 string builder you have 2, and called StringBuilder.toString() twice.
The better and faster way is to use just StringBuilder, without concatenating string manually.
I just checked the bytecode generated with java 1.6.0_26 and the compiler is intelligent and calls toString() only once, but it still creates 2 instances of StringBuilder. Here’s the byte code