正在使用 int + ”“不适合将 Java int 转换为字符串?
因此,我们的计算机科学老师教我们如何通过这样做将 int
转换为 String
:
int i=0;
String s = i+"";
我猜他是这样教我们的,因为这是相对基础的计算机科学(请注意,高中课程),但我想知道与以下内容相比,这是否在某种程度上“不好”:
int i=0;
String s = Integer.toString(i);
它是否更昂贵?习惯不好?提前致谢。
So our computer science teacher taught us how to convert 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
理论上
该指令
执行以下操作:通过调用 Integer.toString(i) 将
i
转换为 String,并将该字符串连接到空字符串。这会导致创建三个 String 对象和一个串联对象。该指令
执行转换,并且仅执行转换。
实际上,
大多数 JIT 编译器都能够将第一个语句优化为第二个语句。如果这种优化是在之前完成的(通过 javac 编译器,在将 Java 源代码编译为字节码时),我不会感到惊讶
In theory
The instruction
does the following: convert
i
to String by callingInteger.toString(i)
, and concatenates this string to the empty string. This causes the creation of three String objects, and one concatenation.The instruction
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)
相当于
so yes 它的效率较低,但除非你在循环中这样做,否则你可能不会注意到它。
[编辑:来自 StriplingWarrior 的评论-谢谢]
is equivalent to
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]
该技术有效,但它依赖于 Java 中字符串连接的魔力(这是涉及运算符重载的少数领域之一),并且可能会让某些人感到困惑。
我发现以下技术更加清晰:
正如其他人提到的,它会产生更简洁的字节码,因为它避免了新 StringBuilder 的隐式构造和随附的方法调用。
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:
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.
Its looks more official....