In Java, you will certainly encounter the int type to string type of case, know its why, summed up and analysis, int type to string type has the following several ways:
- A + ""
- String.valueof (a)
- Integer.tostring (a)
The above three methods in the actual use of the process is not a problem, but there are some differences in efficiency, so write a small program to compare their efficiency:
intA =123456789; Long start = System.currenttimemillis (); for(intI=0; i<100000; i++) {Stringm = A +"";} LongEnd= System.currenttimemillis ();Log. E ("Time","A+\"\" = "+ (End-start); start = System.currenttimemillis (); for(intI=0; i<100000; i++) {Stringn =String. ValueOf (a);}End= System.currenttimemillis ();Log. E ("Time","string.valueof (a) ="+(End-start)); start = System.currenttimemillis (); for(intI=0; i<100000; i++) {Stringn = integer.tostring (a);}End= System.currenttimemillis ();Log. E ("Time","Integer.tostring (a) ="+(End-start));
The last print out execution time:
E/timea+""257E/time: String.valueOf(a140E/time: Integer.toString(a159
You can see that in addition to the efficiency of A + "" This way, the other two ways of efficiency is similar, why? Look at the source!
First look at the following two ways of source code:
String.valueOf(a)->Integer.toString(a)->IntegralToString.intToString(a)->convertInt(null, a)
Integer.toString(a)->IntegralToString.intToString(a)->convertInt(null, a)
You can see that string.valueof is implemented by calling Integer.tostring, and it's no wonder they're so close to efficiency. They will eventually be called into the Convertint function:
Private StaticStringConvertint(Abstractstringbuilder SB,inti) {Boolean negative =false; String Quickresult =NULL;if(I <0) {negative =true; i =-I.;if(I < -) {if(I <0) {//If-n is still negative, n is integer.min_valueQuickresult =" -2147483648"; }Else{quickresult = small_negative_values[i];if(Quickresult = =NULL) {Small_negative_values[i] = Quickresult = i <Ten? Stringof ('-', Ones[i]): Stringof ('-', Tens[i], ones[i]); } } } }Else{if(I < -) {Quickresult = small_nonnegative_values[i];if(Quickresult = =NULL) {Small_nonnegative_values[i] = Quickresult = i <Ten? Stringof (Ones[i]): Stringof (Tens[i], ones[i]); } } }if(Quickresult! =NULL) {if(SB! =NULL) {sb.append0 (Quickresult);return NULL; }returnQuickresult; }intBuflen = One;//Max number of chars in result Char[] buf = (SB! =NULL) ? BUFFER.Get() :New Char[Buflen];intcursor = Buflen;//Calculate digits two-at-a-time till remaining digits fit in + bits while(I >= (1<< -)) {//Compute q = n/100 and r = n% as per "Hacker ' s Delight" 10-8 intQ = (int) ((0x51eb851fL * i) >>>Panax Notoginseng);intR = i- -*q; Buf[--cursor] = Ones[r]; Buf[--cursor] = Tens[r]; i = q; }//Calculate remaining digits one-at-a-time for performance while(I! =0) {//Compute q = N/10 and r = n% as per "Hacker ' s Delight" 10-8 intQ = (0xCCCD* i) >>> +;intR = i-Ten*q; Buf[--cursor] = Digits[r]; i = q; }if(negative) {Buf[--cursor] ='-'; }if(SB! =NULL) {sb.append0 (buf, cursor, buflen-cursor);return NULL; }Else{return NewString (cursor, buflen-cursor, BUF); }}
Analysis, the function of the work can be divided into these steps:
- If a is negative, a is a positive number, and if a is less than 0, it is directly set to Integer.min_value, and if a is less than 100, the results are calculated directly using the tens and ones arrays, plus the '-', which directly returns the result.
- If a is positive and less than 100, the results are returned using the tens and ones arrays for quick calculations.
- If the above two steps are not finished, the description of a is greater than 100 number, can not directly use the Tens and ones array for fast calculation, processing method is 2 bits for one-step loop processing, each time the two bits using tens and ones array to quickly calculate that the two-bit result there is the corresponding position of the array, Until there is only one left; the last one to use the digits array to get 16 binary results is put at the end, returning the result.
So the question is, when a>=100, why do the two while loops use the two numbers of 0X51EB851FL and 0xCCCD? Do not ask me this question, I do not know, but the source author comments written very clear:
// Compute q = n/100 and r = n % 100 as per "Hacker‘s Delight" 10-8
// Compute q = n/10 and r = n % 10 as per "Hacker‘s Delight" 10-8
To see the 10-8 chapters of Hacker's delight.
Then another problem is the tens and ones arrays, directly looking at the code, at a glance:
/** Tens[i] contains the TENS digit of the number I, 0 <= i <=. * /Private Static Final Char[] TENS = {' 0 ',' 0 ',' 0 ',' 0 ',' 0 ',' 0 ',' 0 ',' 0 ',' 0 ',' 0 ',' 1 ',' 1 ',' 1 ',' 1 ',' 1 ',' 1 ',' 1 ',' 1 ',' 1 ',' 1 ',' 2 ',' 2 ',' 2 ',' 2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 ',' 7 ',' 8 ',' 9 ',' 0 ',' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ',' 9 ',};
Each array is 100 in length and is used to handle the 100 digits of the 0~99, and the processing of bits and 10 bits is also clear.
From the point of view of the code, this algorithm in the number less than 100 and greater than 100 processing is not the same, less than 100 of the fast calculation execution time will be much shorter than the way of more than 100, verify that the A variable is modified to 10:
E/timei+"" = 199E/timeString.valueOf() = 7E/timeInteger.toString() = 6
Really short a lot!!!
Look at A + "" way, I admit this way I use the most, because too simple, Java source code to the ' + ' operator overloaded, source I can not find Ah, but from the Internet to find some information:
The Java language provides special support for the string concatenation operator (+), and for conversion of the other object S to strings. String concatenation is implemented through, the StringBuilder (or StringBuffer) class and its Append method. String conversions is implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information in string concatenation and conversion, see Gosling, Joy, and Steele, the Java Language specifi cation.
Address: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
As you can see, the main way of the ' + ' operator is implemented using StringBuilder or StringBuffer, similar to the following:
StringBuilder sb = new StringBuilder();sb.append("");sb.append(i);String strI = sb.toString();
Then look at the source code of append:
StringBuffer.append->IntegralToString.appendInt(this, a)->convertInt(sb, i)
You can see that the ' + ' operator is finally called to the same function, except that the first parameter is not NULL, so it is clear that the ' + ' operator is not performing as efficiently as it was before the new StringBuilder and subsequent operations such as Stringbuilder.tostring, the anti-compilation class file can also draw the same conclusion:
http://stackoverflow.com/a/4105406.
So A + "" way after less use a little, efficiency is not high, also appear not too professional.
After a few weeks of interviews, found that their Java foundation is really weak, so after a lot of strengthening the Java Foundation, from this start, refueling ~
Java int to string efficiency comparison and in-depth analysis of all methods