The Integer parseInt and valueOf

1, Scene

When you need to type String alphanumeric converted to int type, we might use Integer.valueOf () or Integer.parseInt (), both functions can be converted into digital characters integer.

2, source

To Integer.valueOf (String s) for:

    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

Integer.valueOf (String s) first () to convert the string to an int, then Integer.valueOf (int i) converting the basic data types for its package type int Integer by parseInt.

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

To Integer.parseInt (String s), it is a direct call parseInt (String s, int radix), will be converted to a String type int.

    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

3. Conclusion

Integer.valueOf (String s) and Integer.parseInt (String s) is not the same type of return value. Integer.valueOf (String s) returns a package type Integer, and Integer.parseInt (String s) returns a basic data type int.

So, if you only need to get the integer value corresponding to the value of a character string type, then we need not call valueOf, because such values ​​need to do to get plastic surgery after a packing operation will be packaged as int Integer. Use Integer.parseInt (String s) better.

4. Verify

An example to test which method is more efficient.

public class App {
    public static void main(String[] args) {
        String str = "123";
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            Integer.parseInt(str);
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }
}

The results of three runs: 656,614,614

public class App {
    public static void main(String[] args) {
        String str = "123";
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            Integer.valueOf(str);
        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }
}

The results of three runs: 689,697,727

This also explains, Integer.parseInt (String s) is more efficient than Integer.valueOf (String s)

发布了95 篇原创文章 · 获赞 16 · 访问量 5万+

Guess you like

Origin blog.csdn.net/tiankong_12345/article/details/100258909