String valueOf vs concatenation with empty string

后端 未结 10 1713
说谎
说谎 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 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.

提交回复
热议问题