Most efficient way of converting String to Integer in java

后端 未结 11 2050
面向向阳花
面向向阳花 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:43

    Your best bet is to use Integer.parseInt. This will return an int, but this can be auto-boxed to an Integer. This is slightly faster than valueOf, as when your numbers are between -128 and 127 it will use the Integer cache and not create new objects. The slowest is the Apache method.

    private String data = "99";
    
    public void testParseInt() throws Exception {
        long start = System.currentTimeMillis();
        long count = 0;
        for (int i = 0; i < 100000000; i++) {
            Integer o = Integer.parseInt(data);
            count += o.hashCode();
        }
        long diff = System.currentTimeMillis() - start;
        System.out.println("parseInt completed in " + diff + "ms");
        assert 9900000000L == count;
    }
    
    public void testValueOf() throws Exception {
        long start = System.currentTimeMillis();
        long count = 0;
        for (int i = 0; i < 100000000; i++) {
            Integer o = Integer.valueOf(data);
            count += o.hashCode();
        }
        long diff = System.currentTimeMillis() - start;
        System.out.println("valueOf completed in " + diff + "ms");
        assert 9900000000L == count;
    }
    
    
    public void testIntegerConverter() throws Exception {
        long start = System.currentTimeMillis();
        IntegerConverter c = new IntegerConverter();
        long count = 0;
        for (int i = 0; i < 100000000; i++) {
            Integer o = (Integer) c.convert(Integer.class, data);
            count += o.hashCode();
        }
        long diff = System.currentTimeMillis() - start;
        System.out.println("IntegerConverter completed in " + diff + "ms");
        assert 9900000000L == count;
    }
    
    parseInt completed in 5906ms
    valueOf completed in 7047ms
    IntegerConverter completed in 7906ms
    

提交回复
热议问题