Reputation: 129
Following setup:
int a=3;
String b="3";
Both variables represent IDs which are semantically equal. Since the application is for the mobile device, it is very important that the comparison of these variables is done in the most efficient way possible.
Is it efficient to compare these variables with this snippet,
boolean areEqual = Integer.parseInt(b) == a;
or with this one?
boolean areEqual = String.valueOf(a).equals(b);
Upvotes: 8
Views: 1516
Reputation: 328619
If you do know that the string contains a digit, the most efficient way is probably;
boolean areEqual = (a == (b.charAt(0) - '0'));
Upvotes: 1
Reputation: 11892
The highest inefficiency of your code is probably that you convert between int and String at every single comparison. Just do the conversion from String to int right when you get the data at first place. This way you also ensure that any error message reaches your user immediately, e.g. when he/she mistyped the input.
Upvotes: 1
Reputation: 6207
It probably won't matter unless you're doing this comparison many thousands of times. That said, if you look at what each of those statements is doing:
boolean areEqual = Integer.parseInt(b) == a;
This statement parses the String
value once, then does an extremely fast comparison of two primitive int
values.
boolean areEqual = String.valueOf(a).equals(b);
This statement processes a String
once to create the String
value of a
, and then does a String
comparison. More steps, more internal logic, therefore less efficient.
Upvotes: 4