2013年7月29日星期一

Java-String.valueOf conversion and, empty string + type variableconversion and encapsulation class (Integer) way to convert the toStringcomparison.

 

1, an empty string + type variable way to convert

 
  
int i=20; 
String s
=""+i;
 
 

this way actually been two steps, first carried out i.ToString () to i converted to a string, and then the addition operation, where the use of java toString mechanism to prevent conversion.

 

2, String.valueOf way to convert type

 
  
int i=20; 
String s
=String.valueOf(i);
 
 

View source code found in this way is actually to use the wrapper classes (Integer) the toString way to convert.

 
  
1 public static String valueOf(int i) { 
2 return Integer.toString(i);
3 }
 
 

 

3, using the type wrapper class's toString () method

 

 
  
Integer i=20; 
String s
=i.toString();
 
 

view java source found, toString actually new a String.

 

simply the speed of the test.

 

 
  
public class toStringDome { 
public static void main(String[] args)
{
Random ra
=new Random(new java.util.Date().getTime());
String tmp
=null;
int runtimes=1000000;
int range=50;

long startTime=System.currentTimeMillis(); //获取开始时间
for (int i = 0; i <runtimes; i++) {
tmp
=String.valueOf(ra.nextInt(range));
}
long endTime=System.currentTimeMillis(); //获取结束时间

System.out.println(
"使用String.valueOf程序运行时间: "+(endTime-startTime)+"ms");

long startTimeToString=System.currentTimeMillis(); //获取开始时间
for (int i = 0; i <runtimes; i++) {
tmp
= ""+ra.nextInt(range);
}
long endTimeString=System.currentTimeMillis(); //获取结束时间
System.out.println("使用(空串来转换+类型变量)程序运行时间: "+(endTimeString-startTimeToString)+"ms");


Integer temp
=0;
long startTimeToString1=System.currentTimeMillis(); //获取开始时间
for (int i = 0; i <runtimes; i++) {
temp
= ra.nextInt(range);
tmp
=temp.toString();
}
long endTimeString2=System.currentTimeMillis(); //获取结束时间

System.out.println(
"使用Integer的toString程序运行时间: "+(endTimeString2-startTimeToString1)+"ms");


}
}

运行结果:
  

Use String.valueOf run time: 87ms
use (the empty string to convert + type variable) running time: 245ms
use the toString Integer Program running time: 77ms

  
 
 
 

 

After a simple test and found, use (the empty string to convert + type variable) mode conversion ratio String.valueOf with Integer's toString slower than twice.

 

what I understand to use (the empty string to convert + type variable) mode conversion efficiency is slow because in this way actually been two steps, first carried out i.ToString () to convert i to a string, and then the string adder, because strings are immutable, are going to need new memory space to store a new string, the string adder affect the efficiency.

 

 

 

1 条评论: