Is using int + “” bad for converting Java int's to Strings?

╄→гoц情女王★ 提交于 2019-12-23 13:13:29

问题


So our computer science teacher taught us how to convert ints to Strings 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.


回答1:


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)




回答2:


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]




回答3:


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.




回答4:


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....



来源:https://stackoverflow.com/questions/7604379/is-using-int-bad-for-converting-java-ints-to-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!