majji
majji

Reputation: 169

Performance in string comparison

I am checking the performance of the code, I have "".equals(string) in java string value comparison but i have got information like string.trim().length() == 0 gives better performance. Is it true? I have got doubt about this because "".equals(string) will take care even if string is null but for the second thing first we need to null check then only we can trim the string.

which one is better to use: if("".equals(string)) or if(string.trim().length() == 0).

Upvotes: 1

Views: 763

Answers (2)

Radiodef
Radiodef

Reputation: 37845

string.trim().length() == 0 is not the same result as "".equals(string). There is no sense in comparing their performance because they serve different purposes. (However, for the purpose of speculation string.trim().length() == 0 will generally be slower because trim involves an array copy.)

  • string.trim().length() == 0 means "string might not be empty but only contains whitespace".
  • "".equals(string) means "string is only empty or null".

Just for example "".equals(" ") evaluates to false but " ".trim().length() == 0 evaluates to true.

Now the results of the expressions "".equals(string) and string != null && string.length() == 0 are the same. string != null && string.length() == 0 will technically be faster but it really doesn't matter. The difference will be so small, on the scale of a few nanoseconds. This is because "".equals(string) will only get as far as comparing the lengths.

Also in general this is not the type of thing to worry about optimizing.

Upvotes: 4

atish shimpi
atish shimpi

Reputation: 5023

This both approaches are different
approach 1:
if("".equals(string)) - compare your strings it return true if both string having same contents. refer java doc

boolean equals(Object anObject)
Compares this string to the specified object.

and

approach 2 :

if(string.trim().length() == 0) - compare length of string, if both string having same length then it will return true.

To handle null prointer exception, you have to first check whether string is null or not in second approach then call trim() method on string object.

Upvotes: 0

Related Questions