Most efficient way of converting String to Integer in java

后端 未结 11 2010
面向向阳花
面向向阳花 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
    
    0 讨论(0)
  • ParseInt returns an int, not a java.lang.Integer, so if you use tat method you would have to do

    new Integer (Integer.parseInt(number));
    

    I´ve heard many times that calling Integer.valueOf() instead of new Integer() is better for memory reasons (this coming for pmd)

    In JDK 1.5, calling new Integer() causes memory allocation. Integer.valueOf() is more memory friendly.

    http://pmd.sourceforge.net/rules/migrating.html

    In addition to that, Integer.valueOf allows caching, since values -127 to 128 are guaranteed to have cached instances. (since java 1.5)

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

    Herro - kinda new to Java so forgive my ignorance.

    I was searching for a a way to parse a mixed string (letters & numbers) into an INT (kinda like javascript does). Couldn't find anything in the JAVADOC files so after much searching i just wrote a function that does it:

    // This function takes a string mixed with numbers and letters and returns an INT with
    // the first occurrence of a number (INT) in said string, ignoring the rest;
    // -- Basically, loop checks if char is a digit, if yes, puts digit back into new array, if no, puts a whitespace in its place
    // this creates an array with only digits; By converting it to a string and then trimming whitespaces, it gets parsed into an INT
    
    
    public static int mixedStringToInt (String str) {
    
        boolean flag = true;
        boolean isNumber = false;
        final String refNumbers = "0123456789";
    
        int strlen = str.length();
        char[] numberArray = new char[strlen];
        char[] stringArray = str.toCharArray();
    
        for (int i = 0; i < strlen;i++){
            if(refNumbers.indexOf(stringArray[i]) > 0 && flag){
                // if current char is a digit
                isNumber = true;
                while (flag){
                    numberArray[i] = stringArray[i];
                    if(i+1 >= strlen || refNumbers.indexOf(stringArray[i+1]) < 0) flag = false;
                    i++;
                }
            } else {
                // if current char is not a digit
                numberArray[i] = ' ';
            }
        }
        if (isNumber){
            return Integer.valueOf(new String(numberArray).trim());
        } else return 0;
    }
    





    Is this useful for anyone besides me? Did i waste my time writing this as there is already a method that does what i wanted to do?

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

    If efficiency is your concern, use int: it is much faster than Integer.

    Otherwise, class Integer offers you at least a couple clear, clean ways:

    Integer myInteger = new Integer(someString);
    Integer anotherInteger = Integer.valueOf(someOtherString);
    
    0 讨论(0)
  • 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 ) ).

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