Most efficient way of converting String to Integer in java

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

    Another way is this method:

    public class stringtoInteger {
    
        private static int stringtoInteger(String x) {
            String value = "";
            for (int i = 0; i < x.length(); i++) {
                char character = x.charAt(i);
                if (Character.isDigit(character)) {
                    value = value + character;
                }
            }
            return Integer.parseInt(value);
        }
    }  
    

    Hope it helps!

    0 讨论(0)
  • 2020-11-29 08:38

    Here's a good article comparing the performance of different methods of parsing integers

    And here's the code used, with overflow/underflow checks.

    public static int parseInt( final String s )
    {
        if ( string == null )
            throw new NumberFormatException( "Null string" );
    
        // Check for a sign.
        int num  = 0;
        int sign = -1;
        final int len  = s.length( );
        final char ch  = s.charAt( 0 );
        if ( ch == '-' )
        {
            if ( len == 1 )
                throw new NumberFormatException( "Missing digits:  " + s );
            sign = 1;
        }
        else
        {
            final int d = ch - '0';
            if ( d < 0 || d > 9 )
                throw new NumberFormatException( "Malformed:  " + s );
            num = -d;
        }
    
        // Build the number.
        final int max = (sign == -1) ?
            -Integer.MAX_VALUE : Integer.MIN_VALUE;
        final int multmax = max / 10;
        int i = 1;
        while ( i < len )
        {
            int d = s.charAt(i++) - '0';
            if ( d < 0 || d > 9 )
                throw new NumberFormatException( "Malformed:  " + s );
            if ( num < multmax )
                throw new NumberFormatException( "Over/underflow:  " + s );
            num *= 10;
            if ( num < (max+d) )
                throw new NumberFormatException( "Over/underflow:  " + s );
            num -= d;
        }
    
        return sign * num;
    }
    

    And even faster implementation, without overflow/underflow checks.

    public static int parseInt( final String s )
    {
        // Check for a sign.
        int num  = 0;
        int sign = -1;
        final int len  = s.length( );
        final char ch  = s.charAt( 0 );
        if ( ch == '-' )
            sign = 1;
        else
            num = '0' - ch;
    
        // Build the number.
        int i = 1;
        while ( i < len )
            num = num*10 + '0' - s.charAt( i++ );
    
        return sign * num;
    } 
    
    0 讨论(0)
  • 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));
    
    }
    }
    
    0 讨论(0)
  • 2020-11-29 08:41

    Don't even waste time thinking about it. Just pick one that seems to fit with the rest of the code (do other conversions use the .parse__() or .valueOf() method? use that to be consistent).

    Trying to decide which is "best" detracts your focus from solving the business problem or implementing the feature.

    Don't bog yourself down with trivial details. :-)

    On a side note, if your "use case" is specifying java object data types for your code - your BA needs to step back out of your domain. BA's need to define "the business problem", and how the user would like to interact with the application when addressing the problem. Developers determine how best to build that feature into the application with code - including the proper data types / objects to handle the data.

    0 讨论(0)
  • 2020-11-29 08:41

    If efficiency is your concern, then creating an Integer object is much more expensive than parsing it. If you have to create an Integer object, I wouldn't worry too much about how it is parsed.

    Note: Java 6u14 allows you to increase the size of your Integer pool with a command line option -Djava.lang.Integer.IntegerCache.high=1024 for example.

    Note 2: If you are reading raw data e.g. bytes from a file or network, the conversion of these bytes to a String is relatively expensive as well. If you are going to write a custom parser I suggest bypassing the step of conversing to a string and parse the raw source data.

    Note 3: If you are creating an Integer so you can put it in a collection, you can avoid this by using GNU Trove (trove4j) which allows you to store primitives in collections, allowing you to drop the Integer creation as well.

    Ideally, for best performance you want to avoid creating any objects at all.

    0 讨论(0)
  • 2020-11-29 08:41

    I know this isn't amongst your options above. IntegerConverter is ok, but you need to create an instance of it. Take a look at NumberUtils in Commons Lang:

    Commons Lang NumberUtils

    this provides the method toInt:

    static int toInt(java.lang.String str, int defaultValue) 
    

    which allows you to specify a default value in the case of a failure.

    NumberUtils.toInt("1", 0)  = 1
    

    That's the best solution I've found so far.

    0 讨论(0)
提交回复
热议问题