哪种方法更好,为什么?
如果我写
cmissValue = String.valueOf(callDBDatasource.cMiss());
或者
cmissValue = "" + callDBDatasource.cMiss();
应该采取什么方法?
哪种方法更好,为什么?
如果我写
cmissValue = String.valueOf(callDBDatasource.cMiss());
或者
cmissValue = "" + callDBDatasource.cMiss();
应该采取什么方法?
"" + callDBDatasource.cMiss();
将编译为:
new StringBuilder().append("").append(callDBDatasource.cMiss()).toString();
这将创建一个新对象,因此速度明显变慢。看到这个问题:字符串连接真的那么慢吗?
这在这里很有用(“将数字转换为字符串”部分):http ://www.odi.ch/prog/design/newbies.php
不久:
String.valueOf(callDBDatasource.cMiss());
对于那些感兴趣的人,我已经对这两种情况进行了建模并为它们生成了字节码。
这是第一种情况的程序:
import java.util.Random;
public class Test1 {
public static void main(String[] args) {
long l = new Random().nextLong();
String s = String.valueOf(l);
System.out.println(s);
}
}
...这是字节码:
0: new #2; //class java/util/Random
3: dup
4: invokespecial #3; //Method java/util/Random."<init>":()V
7: invokevirtual #4; //Method java/util/Random.nextLong:()J
10: lstore_1
11: lload_1
12: invokestatic #5; //Method java/lang/String.valueOf:(J)Ljava/lang/String;
15: astore_3
16: getstatic #6; //Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_3
20: invokevirtual #7; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: return
这是你所期望的。
现在,这是一个模拟第二种情况的程序:
import java.util.Random;
public class Test2 {
public static void main(String[] args) {
long l = new Random().nextLong();
String s = "" + l;
System.out.println(s);
}
}
...这是字节码:
0: new #2; //class java/util/Random
3: dup
4: invokespecial #3; //Method java/util/Random."<init>":()V
7: invokevirtual #4; //Method java/util/Random.nextLong:()J
10: lstore_1
11: new #5; //class java/lang/StringBuilder
14: dup
15: invokespecial #6; //Method java/lang/StringBuilder."<init>":()V
18: ldc #7; //String
20: invokevirtual #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
23: lload_1
24: invokevirtual #9; //Method java/lang/StringBuilder.append:(J)Ljava/lang/StringBuilder;
27: invokevirtual #10; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
30: astore_3
31: getstatic #11; //Field java/lang/System.out:Ljava/io/PrintStream;
34: aload_3
35: invokevirtual #12; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
38: return
As you can see, many more bytecodes are produced than the first case. You can also see (at 11 through 27) that a StringBuilder
is used to concatenate the values, as mentioned in the accepted answer.