Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it More Efficient to Convert String to Int or Int to String When Checking for Equality?

Tags:

java

android

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);
like image 717
maksuti Avatar asked Aug 16 '13 16:08

maksuti


2 Answers

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.

like image 153
StormeHawke Avatar answered Sep 30 '22 07:09

StormeHawke


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.

like image 38
jboi Avatar answered Sep 30 '22 07:09

jboi