开发者

how to get the String from StringBuilder fast?

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开发者_C百科[] 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 JVM

doSomething( 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

 0  new java.lang.StringBuilder [16]
 3  dup
 4  invokespecial java.lang.StringBuilder() [18]
 7  astore_1 [s]
 8  new java.lang.StringBuilder [16]
11  dup
12  invokespecial java.lang.StringBuilder() [18]
15  aload_1 [s]
16  invokevirtual java.lang.StringBuilder.append(java.lang.Object) : java.lang.StringBuilder [19]
19  invokevirtual java.lang.StringBuilder.toString() : java.lang.String [23]
22  invokestatic my.test.Main.doSomething(java.lang.String) : void [27]
25  return 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜