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