正在使用int +“"将Java int转换为String不好吗? [英] Is using int + "" bad for converting Java int's to Strings?
问题描述
因此,我们的计算机科学老师教我们如何通过以下方法将int
转换为String
:
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.
推荐答案
理论上
说明
String s = i + "";
执行以下操作:通过调用Integer.toString(i)
将i
转换为String,并将此字符串连接为空字符串.这将导致创建三个String对象和一个串联.
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.
说明
String s = Integer.toString(i);
执行转换,仅执行转换.
does the conversion, and only the conversion.
大多数JIT编译器能够将第一条语句优化为第二条语句.如果此优化甚至在以前完成(通过javac编译器,将Java源代码编译为字节码),我也不会感到惊讶.
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)
这篇关于正在使用int +“"将Java int转换为String不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!