问题
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
obj.setSomeString("" + primitiveVariable);
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