Is using int + "" bad for converting Java int's to Strings?
So our computer science teacher taught us how to conver开发者_如何学JAVAt int
s to String
s by doing this:
int i=0;
String s = i+"";
I guess he taught it to us this way since this was relatively basic computer science (high school class, mind you), but I was wondering if this was in some way "bad" when compared to:
int i=0;
String s = Integer.toString(i);
Is it more costly? Poor habit? Thanks in advance.
In theory
The instruction
String s = i + "";
does the following: convert i
to String by calling Integer.toString(i)
, and concatenates this string to the empty string. This causes the creation of three String objects, and one concatenation.
The instruction
String s = Integer.toString(i);
does the conversion, and only the conversion.
In practice
Most JIT compilers are able to optimise the first statement to the second one. I wouldn't be surprised if this optimisation is done even before (by the javac compiler, at compilation of your Java source to bytecode)
i+""
is equivalent to
new StringBuilder().append(i).append("").toString();
so yes it is less efficient, but unless you are doing that in a loop or such you probably won't notice it.
[edited: from comments by StriplingWarrior-thanks]
That technique works but it relies on the magic of string concatenation in Java (which is one of the few areas that involves operator overloading) and might be confusing to some.
I find the following techniques to be more clear:
String.valueOf(123); // => "123"
Integer.toString(123); // => "123"
And as others have mentioned, it results in more concise bytecode since it avoids the implicit construction of a new StringBuilder and the accompanying method calls.
Using that method will compile, since your teacher used that, you might want to use that method when doing stuff in class, but to make it more clean, you might want to use the following code instead.
int i=0;
String s = Integer.toString(s);
Its looks more official....
精彩评论