1. Empty string + Type Variable Conversion
i=20=""+i;
This method actually goes through two steps. First I. ToString () is used to convert I to a string, and then the addition operation is performed. Here the toString mechanism of java is used for conversion.
2. String. valueOf type conversion
i=20=String.valueOf(i);
Check the source code and find that this method actually uses the toString method of the encapsulation class (Integer) for conversion.
String valueOf( }
3. Use the toString () method of the encapsulation class
Integer i=20=i.toString();
= Random (= runtimes = 1000000 range = 50 startTime = System. currentTimeMillis (); (I = 0; I <runtimes; I ++ = endTime = System. currentTimeMillis (); "use String. valueOf program running time: "+ (endTime-startTime) +" ms "startTimeToString = System. currentTimeMillis (); (I = 0; I <runtimes; I ++ = "" + endTimeString = System. currentTimeMillis (); System. out. println ("use (empty string to convert + type variable) running time:" + (endTimeString-startTimeToString) + "ms" = 0 startTimeToString1 = System. currentTimeMillis (); (I = 0; I <runtimes; I ++ = endTimeString2 = System. currentTimeMillis (); "use Integer toString runtime:" + (endTimeString2-startTimeToString1) + "ms"
Running time with String. valueOf: 87 ms
Program running time: 245 ms using (empty String Conversion + type variable)
The running time of the toString using Integer is 77 ms.
After a simple test, it is found that the (empty String Conversion + type variable) conversion is more than twice slower than the String. valueOf and Integer toString conversion.
I personally understand that the efficiency of the conversion using (empty String Conversion + type variable) method is slow because this method has actually gone through two steps, first I. toString () converts I to a string and then performs addition operations on the string. Because the string is unchangeable, a new memory space is required to store the new string, the string addition operation affects the efficiency.