一尘不染

字符串valueOf与空字符串的串联

java

我正在从事Java代码优化。我不清楚String.valueOf+""符号之间的区别:

int intVar = 1;
String strVar = intVar + "";
String strVar = String.valueOf(intVar);

第2行和第3行有什么区别?


阅读 258

收藏
2020-09-08

共1个答案

一尘不染

public void foo(){
int intVar = 5;
String strVar = intVar+"";    
}

这种方法使用StringBuilder创建结果字符串

public void foo();
  Code:
   0:   iconst_5
   1:   istore_1
   2:   new     #2; //class java/lang/StringBuilder
   5:   dup
   6:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   9:   iload_1
   10:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(I)Ljava/lan
g/StringBuilder;
   13:  ldc     #5; //String
   15:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
   18:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/la
ng/String;
   21:  astore_2
   22:  return

public void bar(){
int intVar = 5;
String strVar = String.valueOf(intVar);
}

此方法仅调用的静态方法String来获取int的String版本

public void bar();
  Code:
   0:   iconst_5
   1:   istore_1
   2:   iload_1
   3:   invokestatic    #8; //Method java/lang/String.valueOf:(I)Ljava/lang/Stri
ng;
   6:   astore_2
   7:   return

依次调用
Integer.toString()

2020-09-08