views:

230

answers:

5
+6  Q: 

String conversions

I have a method which takes String argument.In some cases i want to pass int value to that method.For invoking that method i want to convert int into String.For that i am doing the following

    aMethod(""+100);

One more option is

    aMethod(String.valueOf(100));

Both are correct.I don't know which is appropriate?Which gives better performance?

Mostly this is happen in GWT.In GWT for setting size of panels and widgets i want to do this.

Can anyone give suggestion?

+4  A: 

Using + on strings creates multiple string instances, so using valueOf is probably a bit more performant.

Fabian Steeg
and as the Jon Skeet article points out, valueOf(foo) protects you in any future refactoring should the primitive's type need to be changed... Integer.toString(foo) does not provide this protection.
Lee Harold
+11  A: 

Good article by Jon Skeet about your question's topic: String conversions - the Good, the Okay-I-Suppose, and the Utterly Horrible

Johannes Schaub - litb
And I here I was assuming no-one read that one, it's so old... but I still agree with it :)
Jon Skeet
Wow good link, thanks :)
Midday
Thanks a lot to Jon Skeet for the good Article.
BlackPanther
+1  A: 

Normally you'd use Integer.toString(int) or String.valueOf(int). They both return the same thing, and probably have identical implementations. Integer.toString(int) is a little easier to read at a glance though, IMO.

patros
A: 

I'd assume that this:

aMethod(""+100);

turns into this by the compiler:

aMethod(new StringBuilder("").append(String.valueOf(100)).toString());

So the option of calling the String.valueOf directly is probably the better choice. You could always compile them and compare the bytecode to see for sure.

John Gardner
+2  A: 

Since you're mostly using it in GWT, I'd go with the ""+ method, since it's the neatest looking, and it's going to end up converted to javascript anyway, where there is no such thing as a StringBuilder.

Please don't hurt me Skeet Fanboys ;)

rustyshelf