String valueOf vs concatenation with empty string

2020-01-24 12:43发布

I am working in Java code optimization. I'm unclear about the difference between String.valueOf or the +"" sign:

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

What is the difference between line 2 and 3?

标签: java
10条回答
爷的心禁止访问
2楼-- · 2020-01-24 12:52

Ask yourself the purpose of the code. Is it to:

  • Concatenate an empty string with a value
  • Convert a value to a string

It sounds much more like the latter to me... which is why I'd use String.valueOf. Whenever you can make your code read in the same way as you'd describe what you want to achieve, that's a good thing.

Note that this works for all types, and will return "null" when passed a null reference rather than throwing a NullPointerException. If you're using a class (not an int as in this example) and you want it to throw an exception if it's null (e.g. because that represents a bug), call toString on the reference instead.

查看更多
倾城 Initia
3楼-- · 2020-01-24 12:54
public void foo(){
int intVar = 5;
String strVar = intVar+"";    
}

This approach uses StringBuilder to create resultant String

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);
}

This approach invokes simply a static method of String to get the String version of int

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

which in turn calls Integer.toString()

查看更多
贪生不怕死
4楼-- · 2020-01-24 12:55

I'd prefer valueOf(), because I think it's more readable and explicit.

Any concerns about performance are micro-optimizations that wouldn't be measurable. I wouldn't worry about them until I could take a measurement and see that they made a difference.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-01-24 12:58

Concatenating Strings and other variables actually uses String.valueOf() (and StringBuilder) underneath, so the compiler will hopefully discard the empty String and produce the same bytecodes in both cases.

查看更多
爷、活的狠高调
6楼-- · 2020-01-24 12:58

Well, if you look into the JRE source code, Integer.getChars(...) is the most vital method which actually does the conversion from integer to char[], but it's a package-private method.
So the question is how to get this method called with minimum overhead.
Following is an overview of the 3 approaches by tracing the calls to our target method, please look into the JRE source code to understand this better.

  1. "" + intVar compiles to :
    new StringBuilder() => StringBuilder.append(int) => Integer.getChars(...)
  2. String.valueOf(intVar) => Integer.toString(intVar) => Integer.getChars(...)
  3. Integer.toString(intVar) => Integer.getChars(...)

The first method unnecessarily creates one extra object i.e. the StringBuilder.
The second simply delegates to third method.
So you have the answer now.

PS: Various compile time and runtime optimizations come into play here. So actual performance benchmarks may say something else depending on different JVM implementations which we can't predict, so I generally prefer the approach which looks efficient by looking at the source code.

查看更多
Bombasti
7楼-- · 2020-01-24 13:02

The first line is equivalent to

String strVal = String.valueOf(intVar) + "";

so that there is some extra (and pointless) work to do. Not sure if the compiler optimizes away concatenations with empty string literals. If it does not (and looking at @Jigar's answer it apparently does not), this will in turn become

String strVal = new StringBuilder().append(String.valueOf(intVar))
                      .append("").toString();

So you should really be using String.valueOf directly.

查看更多
登录 后发表回答