Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Comparing ints and Strings - Performance

Tags:

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

like image 864
Justin Avatar asked Apr 13 '13 05:04

Justin


People also ask

Is it faster to compare string or int?

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.

Can you compare int and string in Java?

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

Can you use == to compare ints in Java?

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

Can you use compareTo for strings?

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.


2 Answers

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.

like image 78
dhruv chopra Avatar answered Sep 28 '22 15:09

dhruv chopra


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

like image 34
Ankur Shanbhag Avatar answered Sep 28 '22 17:09

Ankur Shanbhag