Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 717
Aravind Yarram Avatar asked Jun 23 '09 03:06

Aravind Yarram


People also ask

What is the fastest way to convert a string to a number?

Converting strings to numbers is extremely common. The easiest and fastest (jsPerf) way to achieve that would be using the + (plus) operator. You can also use the - (minus) operator which type-converts the value into number but also negates it.

Which is used to convert a string to int in java?

The method generally used to convert String to Integer in Java is parseInt() of String class.

Can you convert strings to ints?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.


1 Answers

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.

like image 120
Peter Lawrey Avatar answered Oct 08 '22 12:10

Peter Lawrey