Most efficient way of converting String to Integer in java

后端 未结 11 2034
面向向阳花
面向向阳花 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 09:01

    I'm always amazed how quickly many here dismiss some investigation into performance problems. Parsing a int for base 10 is a very common task in many programs. Making this faster could have a noticable positive effect in many environments.

    As parsing and int is actually a rather trivial task, I tried to implement a more direct approach than the one used in the JDK implementation that has variable base. It turned out to be more than twice as fast and should otherwise behave exactly the same as Integer.parseInt().

    public static int intValueOf( String str )
    {
        int ival = 0, idx = 0, end;
        boolean sign = false;
        char ch;
    
        if( str == null || ( end = str.length() ) == 0 ||
           ( ( ch = str.charAt( 0 ) ) < '0' || ch > '9' )
              && ( !( sign = ch == '-' ) || ++idx == end || ( ( ch = str.charAt( idx ) ) < '0' || ch > '9' ) ) )
            throw new NumberFormatException( str );
    
        for(;; ival *= 10 )
        {
            ival += '0'- ch;
            if( ++idx == end )
                return sign ? ival : -ival;
            if( ( ch = str.charAt( idx ) ) < '0' || ch > '9' )
                throw new NumberFormatException( str );
        }
    }
    

    To get an Integer object of it, either use autoboxing or explicit

    Interger.valueOf( intValueOf( str ) ).

提交回复
热议问题