tusar
tusar

Reputation: 3424

difference between String.valueOf(int) , `+` string operator and Integer.toString(int)

Not confident about whether this will be downvoted or closed... I need expert opinion on this.

The context is in our application, we have written code like :

//countryId is an integer, searchCity() expects two String parameters
loadCity(countryName , countryId + "");

Will it make any difference if I change (I am being forced to do so) the call like :

loadCity(countryName, String.valueOf(countryId));

Or,

loadCity(countryName, Integer.toString(countryId));

Will this make any difference in sense of performance?

Upvotes: 1

Views: 1749

Answers (5)

Wouter Verleur
Wouter Verleur

Reputation: 61

A search on both methods informed me all of these are equivalent:

    String.valueOf(countryId) 
    Integer.toString(countryId) 
    countryId.toString() //Only if countryId is an Integer

Because they all call:

    Integer.toString(countryId, 10) 

The only difference is if you wish to use a different radix, ie:

   Integer.toString(countryId, radix)

Personally I think countryId.toString() reads better when using an Integer. Otherwise Integer.toString(countryId) is the way to go. But that is just my personal opinion. Performance-wise you should use Integer.toString(countryId, 10).

I think that adding an empty string to an int to convert it to a String is a bad practice.

Upvotes: 0

klonq
klonq

Reputation: 3587

For the example you have given, the answer will really depend on the type of 'integer' you are using.

loadCity(countryName , countryId + "");

For an Integer object this is equivelent to :

loadCity(countryName, countryId.toString() + "");

Whereas for an int primitive, this code is equivelent to :

loadCity(countryName, String.valueOf(countryId) + "");

In either case, as ArjunShankar pointed out there is a good chance that the compiler has optimised your code anyway. So if your question is 'do I go back and refactor all my code?', then I would say 'don't sweat the small stuff'. But in the future use a more conventional approach to avoid the down votes.

Upvotes: 2

Nagaraju Badaeni
Nagaraju Badaeni

Reputation: 900

They are same.... because the method String.valueOf(int i) implicitly calls Integer.toString(i, 10);

Upvotes: 0

mre
mre

Reputation: 44240

I'd say the main difference is readability. There's no use in micro-benching here. IMHO String#valueOf reads the best.

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120188

From the docs of String.valueOf

"The representation is exactly the one returned by the Integer.toString method of one argument."

I would use String.valueOf because you can use it on more then just Integers, i.e. you don't have to know whether you have an int, double, bool, etc....

Upvotes: 1

Related Questions