Most efficient way of converting String to Integer in java

后端 未结 11 2027
面向向阳花
面向向阳花 2020-11-29 08:00

There are many ways of converting a String to an Integer object. Which is the most efficient among the below:

Integer.valueOf()
Integer.parseInt()
org.apache         


        
11条回答
  •  攒了一身酷
    2020-11-29 08:38

    I tried a comparison of valueOf, parseInt, Ints.tryParse, NumberUtils.createInteger and NumberUtils.toInt with the program below. I was on jdk 1.8.0

    As expected, the methods that did not need to create an Integer object were the fastest. My results were:

    valueOf took: 77
    parseInt took: 61
    Ints.tryParse took: 117
    numberUtils.createInteger took: 169
    numberUtils.toInt took: 63 
    

    So the summary is:

    If you can get by using an int, use Integer.parseInt.

    If you absolutely need an Integer, use Integer.valueOf

    If you need the convenience of not handling exceptions when you parse, or if you are unsure of the format of the input (i.e its a string that need not be a number) use Ints.tryParse

    The code I used was:

    public class HelloWorld {
    
    public static int limit = 1000000;
    public static String sint = "9999";
    
    public static void main(String[] args) {
    
        long start = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
           Integer integer = Integer.valueOf(sint);
        }
        long end = System.currentTimeMillis();
    
        System.out.println("valueOf took: " + (end - start));
    
    
        start = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
            int integer = Integer.parseInt(sint);
        }
        end = System.currentTimeMillis();
    
        System.out.println("parseInt took: " + (end - start));
    
    
        start = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
            int integer = Ints.tryParse(sint);
        }
        end = System.currentTimeMillis();
    
        System.out.println("Ints.tryParse took: " + (end - start));
    
    
        start = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
            Integer integer = NumberUtils.createInteger(sint);
        }
        end = System.currentTimeMillis();
    
        System.out.println("numberUtils.createInteger took: " + (end - start));
    
        start = System.currentTimeMillis();
        for (int i = 0; i < limit; i++) {
            int integer = NumberUtils.toInt(sint);
        }
        end = System.currentTimeMillis();
    
        System.out.println("numberUtils.toInt took: " + (end - start));
    
    }
    }
    

提交回复
热议问题