I have a String and an int, lets say: String str = "12345";
and int num = 12345;
. What is the fastest way of seeing if they are the same, str.equals("" + num)
or num == Integer.parseInt(str)
(Or is there a faster way?)?
This is the source code for Integer.parseInt and String.equals
So, comparing integers are far better than comparing two long strings character by character. This is much faster and less CPU utilization than comparing character by character.
If you want to compare their string values, then you should convert the integer to string before comparing (i.e. using String. valueOf() method). If you compare as integer values, then 5 is less than "123". If you compare as string values, then 5 is greater than "123".
To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).
Java String compareTo() MethodThe compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
num == Integer.parseInt(str)
is going to faster than str.equals("" + num)
str.equals("" + num)
will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)
num == Integer.parseInt(str)
will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)
To summarize both are O(n) - but str.equals("" + num)
has a higher constant and so is slower.
I think num == Integer.parseInt(str)
is a better way of doing comparison. Because str.equals("" + num)
this is not the ideal way how you should compare integer values and also it will create unnecessary String constant objects in the String pool (which hampers performance).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With