String.valueOf(long a)和连接(“”+ a)之间的区别

时间:2013-03-09 16:46:17

标签: java

哪种方法更好,为什么?

如果我写

cmissValue = String.valueOf(callDBDatasource.cMiss());

cmissValue = "" + callDBDatasource.cMiss();

该方法应该是什么?

3 个答案:

答案 0 :(得分:8)

"" + callDBDatasource.cMiss();

将编译为:

new StringBuilder().append("").append(callDBDatasource.cMiss()).toString();

这将创建一个新对象,因此显着更慢。请参阅此问题:Is string concatenaion really that slow?

答案 1 :(得分:3)

这在此处很有用(“将数字转换为字符串”部分):http://www.odi.ch/prog/design/newbies.php

不久:

    String.valueOf(callDBDatasource.cMiss());

答案 2 :(得分:2)

对于那些感兴趣的人,我已经为这两种情况建模并为它们生成了字节码。

这是第一个案例的程序:

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

如您所见,生成的字节码比第一种情况多得多。您还可以看到(在11到27之间)StringBuilder用于连接值,如接受的答案中所述。