您的位置:首页 > 其它

int 转 String 的效率大比拼

2010-12-15 00:07 211 查看
先说一下我自己的实验结论吧,int 转 String 的三个方法(假设 x 是int 型变量):
①""+x,效率最低;
②Integer.toString( x ),效率最高;
③String.valueOf( x ),效率比②低一点比①好不少。
详情如下:
有一哥们出了个题目,本来不想看的,太简单,不过看看别人的算法也是不错的。题目见下面:



看见一个很给力的解答,引用上来:



 
看到这个答案,我就知道自己没有白去看帖子了,呵呵。不过上面的 int len = (“” + x).length() 让我想起了另一个 int 转 String 的方法: Integer.toString(x) ,不知道哪个效率高一点,自己分析了一下,前者多了一个 "" 对象,而后者比较完美,应该是后者效率高点吧。如是就百度了一下,发现还有另外一种方法: String.valueOf(x),百度的结果是 Integer.toString(x) 效率大于 String.valueOf(x) 约等于 ""+x 。自己随即也自己此写了断代码验证了一下,实践出真知嘛。
代码如下:
package cn.coolong.com;


 


public class Wish {


public static void main(String[] args) {


toString1();


toString2();


toString3();


}


 


public static void toString1() {


String str = null;


long start = System.currentTimeMillis();


for (int i = 0; i <= 1000000; i++) {


str = i + "";


}


System.out.println(System.currentTimeMillis() - start);


}


 


public static void toString2() {


String str = null;


long start = System.currentTimeMillis();


for (int i = 0; i <= 1000000; i++) {


str = Integer.toString(i);


}


System.out.println(System.currentTimeMillis() - start);


}


 


public static void toString3() {


String str = null;


long start = System.currentTimeMillis();


for (int i = 0; i <= 1000000; i++) {


str = String.valueOf(i);


}


System.out.println(System.currentTimeMillis() - start);


}


}


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
c{ color : #606060;}

实验了几次,结果如下:

MethodstoString1()toString2()toString3()
1498164181
2520166180
3456153160
4444149160
5567189200
6457150165
 

可见, "" + x 的效率最低;String.valueOf( x ) 和 Integer.toString( x ) 的效率相当,但是 Integer.toString( x )的效率稍微有点领先。

---EOF---

至于为什么和别人的结果不一样,我也不太清楚,可能是 JDK 版本不同吧,其他评测请点击:http://blog.sina.com.cn/s/blog_4abc0dc50100dvgb.html .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: