Aravind Yarram
Aravind Yarram

Reputation: 80166

Most efficient way of converting String to Integer in java

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.commons.beanutils.converters.IntegerConverter

My usecase needs to create wrapper Integer objects...meaning no primitive int...and the converted data is used for read-only.

Upvotes: 30

Views: 62650

Answers (11)

Jay Askren
Jay Askren

Reputation: 10444

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;
} 

Upvotes: 6

Jonathan Holloway
Jonathan Holloway

Reputation: 63652

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.

Upvotes: 11

Somaiah Kumbera
Somaiah Kumbera

Reputation: 7489

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));

}
}

Upvotes: 5

malitha619
malitha619

Reputation: 1

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!

Upvotes: 0

Matt
Matt

Reputation: 278

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?

Upvotes: 0

Ron Savage
Ron Savage

Reputation: 11079

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.

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533472

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.

Upvotes: 30

x4u
x4u

Reputation: 14077

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 ) ).

Upvotes: 12

brianegge
brianegge

Reputation: 29852

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

Upvotes: 24

Jim Ferrans
Jim Ferrans

Reputation: 31012

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);

Upvotes: 5

Tom
Tom

Reputation: 45104

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)

Upvotes: 0

Related Questions