Subscribe:

Friday, April 13, 2012

Java notes : convert Int to String (efficiency comparison)


Basically, there are three methods to convert an integer to string.
( i is the integer created before)

  1. String.valueOf(i)
  2. Integer.toString(i)
  3. i + ""

What is the efficiency for these methods?


I have written a small program to convert 1 millions int to string for testing:
for(int i=0;i<1000000;i++)
strArr1[i] = String.valueOf(intArr[i]);     
for(int i=0;i<1000000;i++){   
strArr2[i] = Integer.toString(intArr[i]);   
for(int i=0;i<1000000;i++){   
strArr3[i] = new String(""+intArr[i]);     
"System.currentTimeMillis();" is used to record the time used by 3 for loops. I run the test for many times and get the avg time.
String.valueOf(i):760.08
Integer.toString(i):717.48
i+"":1611.98
From the result, you can see that using Integer.toString(i) is the fastest method and the slowest methods is concat i with an empty string.

Let's look into the source to see why Integer.toString(i) is faster than String.valueOf(i):

In String class:
public static String valueOf(int i) {
        return Integer.toString(i, 10);
}
In Integer class:
public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(0, size, buf);
}

public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
   radix = 10;
/* Use the faster version */
if (radix == 10) {
   return toString(i);
}
Actually, when you use String.valueOf(i), it will call the toString(i,10) method in the Integer and the toString(i,10) will then call the toString(i) to finish the process.
More instructions = More time

For the process of i+"", I am still finding what is behind. (will update when I get the answer)

No comments:

Post a Comment