Reputation: 5581
I know that String.valueOf(int)
enables caching and often does not cause an extra object to be created, but does ("" + 1)
get some kind of compiler optimization?
Which one should be used?
EDIT: String.valueOf(int) does not enable caching, Integer.valueof(int) does.
Upvotes: 3
Views: 126
Reputation: 533500
Using String.valueOf(int)
is reasonable optimal for the application.
""+i
may be more optimal for you and unless you have loads of time and a resource limited device, saving your time may be more valuable than saving a micro-second of CPU time.
Upvotes: 0
Reputation:
"" + 1
is a bad habit in my opinion and as far as I know it is not optimized in any way.
Do stick with String.valueOf(int)
.
Upvotes: 5
Reputation: 1500504
No, String.valueOf
doesn't perform any caching. However, it's more readable than "" + 1
(which also doesn't perform any caching) because it says what you want to do.
"" + 1
talks about string concatenation and an empty string, neither of which have anything to do with your aim - which is to get the value of an integer, as a String
.
String.valueOf
says exactly what you want to do, so use that.
Upvotes: 5
Reputation: 33068
Choose explicit conversions over implicit ones.
String.valueOf(int)
tells you exactly what it is doing.
Although, I always use Integer.toString(int)
because I read this as the toString
method for a primitive int
.
Upvotes: 0
Reputation: 4182
They are both equivalent and it is more a matter of personal taste. Personally, I prefer String.valueOf(int).
Upvotes: 0