'Integer.parseInt is best way to convert String to Int in Java?
We normally use Integer.parseInt method for String
to Integer
conversion in JAVA
, but when I check the implementation of parseInt method it goes way deep that I think initially. Below I m sharing how deep parseInt goes:
Integer.parseInt(String s) -> Integer.parseInt(String s, int radix) -> Character.digit(char ch, int radix) -> Character.digit(int codePoint, int radix) -> (Based on instance call will go to digit(int ch, int radix))
Note: There are total 7 different Instance define for CharacterData, and one of them will peak for digit.
As per above details it's look like ParseInt is not that easy what it look initially, so will it be not best to convert String to Integer?
However, I followed one discussion (link I lost at moment) and found below method which is pretty fast in terms of performance.
static int getNumber(String number){
int result = 0;
int startIndex = 0;
for(int i=startIndex;i<number.length();i++){
result = result*10+number.charAt(i)-'0';
}
return result;
}
and below is the performance test result which I found for both methods.
Value :123456789 , Integer->parseInt Converted in 22000 nanosec.
Value :123456789 , getNumber Converted in 5000 nanosec.
So what will be the best way to convert String to Integer, Integer.parseInt or getNumber method ?
Solution 1:[1]
parseInt
is the way to go. The Integer documentation says
Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
parseInt
is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.
Solution 2:[2]
I invite you to look at the source code of the parseInt function. Your naïve function is faster, but it also does way less. Edge cases, such as the number being to large to fit into an int
or not even being a number at all, will produce undetectable bogus results with your simple function.
It is better to just trust that the language designers have done their job and have produced a reasonably fast implementation of parsing integers. Real optimization is probably elsewhere.
Solution 3:[3]
I thinks you should follow the language designers said, as we know that, if use the getNumber method, it can't detect error when the string don't contain a number character. also can see convert-string-to-int
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ggovan |
Solution 2 | Bert Peters |
Solution 3 | Asen |