Is it more efficient to convert a string to Int or Int to string when checking for equality?

The following setting:

int a=3; String b="3"; 

Both variables are identifiers that are semantically equal. Since the application is intended for a mobile device, it is very important that these variables are compared in the most efficient way.

Is it effective to compare these variables with this fragment,

 boolean areEqual = Integer.parseInt(b) == a; 

or with that?

 boolean areEqual = String.valueOf(a).equals(b); 
+8
java android
source share
3 answers

It probably doesn't matter if you don't make this comparison many thousands of times. However, if you look at what each of these statements does:

boolean areEqual = Integer.parseInt(b) == a; This statement parses the String value once, then makes a very quick comparison of two primitive int values.

boolean areEqual = String.valueOf(a).equals(b); This statement processes a String once to create a String a , and then compares String . Faster steps, more internal logic, therefore less effective.

+4
source share

The highest inefficiency of your code is probably that you convert between int and String with each separate comparison. Just do the conversion from String to int right when you get the data in the first place. In this way, you also guarantee that the error message reaches your user immediately, for example. when he / she mistakenly enters an input.

+1
source share

If you know that a string contains a digit, perhaps the most efficient way is to

 boolean areEqual = (a == (b.charAt(0) - '0')); 
+1
source share

All Articles