String valueOf vs concatenation with empty string

后端 未结 10 1557
说谎
说谎 2020-11-27 05:05

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

int intVar = 1;         


        
相关标签:
10条回答
  • 2020-11-27 05:55

    Even though answers here are correct in general, there's one point that is not mentioned.

    "" + intVar has better performance compared to String.valueOf() or Integer.toString(). So, if performance is critical, it's better to use empty string concatenation.

    See this talk by Aleksey Shipilëv. Or these slides of the same talk (slide #24)

    0 讨论(0)
  • 2020-11-27 05:58

    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.

    0 讨论(0)
  • 2020-11-27 05:59

    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.

    0 讨论(0)
  • 2020-11-27 06:00

    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.

    0 讨论(0)
提交回复
热议问题