String.valueOf(someVar) vs (“” + someVar) [duplicate]

眉间皱痕 提交于 2021-01-27 21:39:01

问题


I want to know the difference in two approaches. There are some old codes on which I'm working now, where they are setting primitive values to a String value by concatenating with an empty String "".

obj.setSomeString("" + primitiveVariable);

But in this link Size of empty Java String it says that If you're creating a separate empty string for each instance, then obviously that will take more memory.

So I thought of using valueOf method in String class. I checked the documentation String.valueOf() it says If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

So which one is the better way

  1. obj.setSomeString("" + primitiveVariable);
  2. obj.setSomeString(String.valueOf(primitiveVariable));

The above described process of is done within a List iteration which is having a size of more than 600, and is expected to increase in future.


回答1:


When you do "" that is not going to create an Object. It is going to create a String literal. There is a differenc(How can a string be initialized using " "?) actually.

Coming to your actual question,

From String concatenation docs

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

So unnecissarly you are creating StringBuilder object and then that is giving another String object.

However valueOf directly give you a String object. Just go for it.

Besides the performance, just think generally. Why you concatenating with empty string, when actually you want to convert the int to String :)




回答2:


Q. So which one is the better way

A. obj.setSomeString(String.valueOf(primitiveVariable)) is usually the better way. It's neater and more domestic. This prints the value of primitiveVariable as a String, whereas the other prints it as an int value. The second way is more of a "hack," and less organized. The other way to do it is to use Integer.toString(primitiveVariable), which is basically the same as String.valueOf.

Also look at this post and this one too



来源:https://stackoverflow.com/questions/45386769/string-valueofsomevar-vs-somevar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!