20

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

Justin
  • 24,288
  • 12
  • 92
  • 142

3 Answers3

22

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.

dhruv chopra
  • 490
  • 3
  • 11
  • That is a completely flawed and WRONG logic. O(n)+O(n) is still O(n) - you do not add those numbers as that notation only tells you about its asymptotic growth. And the rest is just as wrong. Java will usually notice that "" is an empty string so no concatination. And converting an integer to a string is, in general, quite a bit faster than the other way around as it is a known valid conversion, where as the other way around has to deal with many special cases. – ABaumstumpf Jan 13 '21 at 11:20
5

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

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
1

Guess you might also be able to use this to compare........

int p = 1234;
String Int = "1234";
String string = String.valueOf(p);
System.out.println(string + Int);
System.out.println(string.equals(Int));
code here
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97