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 13:05
String strVar1 = intVar+"";
String strVar2 = String.valueOf(intVar);

strVar1 is equvalent to strVar2, but using int+emptyString "" is not elegant way to do it.

using valueOf is more effective.

查看更多
孤傲高冷的网名
3楼-- · 2020-01-24 13:06

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)

查看更多
够拽才男人
4楼-- · 2020-01-24 13:07

From the point of optimization , I will always prefer the String.valueOf() between the two. The first one is just a hack , trying to trick the conversion of the intVar into a String because the + operator.

查看更多
三岁会撩人
5楼-- · 2020-01-24 13:11

Using String.valueOf(int), or better, Integer.toString(int) is relatively more efficient for the machine. However, unless performance is critical (in which case I wouldn't suggest you use either) Then ""+ x is much more efficient use of your time. IMHO, this is usually more important. Sometimes massively more important.

In other words, ""+ wastes an object, but Integer.toString() creates several anyway. Either your time is more important or you want to avoid creating objects at all costs. You are highly unlikely to be in the position that creating several objects is fine, but creating one more is not.

查看更多
登录 后发表回答