说我有:
int someValue = 42;
Run Code Online (Sandbox Code Playgroud)
现在我想将该int值转换为String.哪种方式更有效?
// One
String stringValue = Integer.toString(someValue);
// Two
String stringValue = String.valueOf(someValue);
// Three
String stringValue = someValue + "";
Run Code Online (Sandbox Code Playgroud)
我只是好奇,如果有任何真正的差异或一个比另一个更好?
cob*_*bal 73
测试了10号的10米任务
One:
real 0m5.610s
user 0m5.098s
sys 0m0.220s
Two:
real 0m6.216s
user 0m5.700s
sys 0m0.213s
Three:
real 0m12.986s
user 0m11.767s
sys 0m0.489s
Run Code Online (Sandbox Code Playgroud)
一个似乎赢了
编辑:在Mac OS X 10.5下,JVM是标准的'/ usr/bin/java'
java version "1.5.0_16" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284) Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)
更多编辑:
代码请求
public class One {
public static void main(String[] args) {
int someValue = 10;
for (int i = 0; i < 10000000; i++) {
String stringValue = Integer.toString(someValue);
}
}
}
Run Code Online (Sandbox Code Playgroud)
情况2和3类似地
运行使用
javac *.java; time java One; time java Two; time java Three
Run Code Online (Sandbox Code Playgroud)
查看JRE的源代码,您可能会看到差异.或者没有.事实上,Strinv.valueOf(int foo)实现如下:
public static String valueOf(int i) {
return Integer.toString(i, 10);
}
Run Code Online (Sandbox Code Playgroud)
和Integer.toString(int foo,int radix)
public static String toString(int i, int radix) {
...
if (radix == 10) {
return toString(i);
}
...
}
Run Code Online (Sandbox Code Playgroud)
这意味着如果使用基数10,最好直接调用Integer.toString(int foo).对于其他情况,请使用Integer.toString(int foo,int radix).
concat解决方案首先将int值转换为String,然后再与空String连接.这显然是最昂贵的情况.
前两个示例实际上是相同的,因为String.valueOf(int)使用Integer.toString(int)方法.第三个是丑陋的,可能效率较低,因为Java中的连接速度很慢.
(David Hanak对面.)
即使根据cobbal的测量结果,#1似乎是最快的,我强烈建议使用Integer.toString().我的理由是这个调用显式地包含了参数的类型,所以如果你以后决定将它从int更改为double,很明显这个调用已经改变了.如果它是二进制格式你也会这样做,不是吗?与#2相比,#1的速度增益很小,而众所周知,"过早优化是所有邪恶的根源".
| 归档时间: |
|
| 查看次数: |
17074 次 |
| 最近记录: |