Tuesday, December 14, 2010

How to check for an empty or blank string

PMD gives me an warning every now and then about "String.trim().length() == 0 is an inefficient way to validate an empty string". This message always annoys me because it doesn't offer an alternative. Looks like I need to fix the PMD plugin for jEdit, because if you read the rest of the rule in PMD, it does:




Name: InefficientEmptyStringCheck
Description: String.trim().length() is an inefficient way to check if a
String is really empty, as it creates a new String object just to check its
size. Consider creating a static function that loops through a string,
checking Character.isWhitespace() on each character and returning false if a
non-whitespace character is found.
Error Message: String.trim().length()==0 is an inefficient way to validate
an empty String.

So I set about testing if this is the best way to check for an empty/blank String.
The PMD suggestion seems to be correct. The best I've come up with is this:





   1 public static boolean isEmptyOrBlank(String s) {
   2     if (s == null || s.length() == 0) {
   3         return true;
   4     }
   5     for (int i = 0; i < s.length(); i++){
   6         if (!Character.isWhitespace(s.charAt(i))){
   7             return false;
   8         }
   9     }
  10     return true;
  11 }


This code works for either Java 1.5 or Java 1.6 equally well, performance-wise.
The Java 1.6 isEmpty method simply checks if the length of the string is 0,
so it really doesn't bring any performance enhancement to this issue.

The simple check is done on line 2.

  • If the string is null, then it is obviously empty.
  • If the length of the string is 0, then it is obviously empty.
The check for blankness, or all whitespace is on lines 5 through 7. No new objects are
created during this loop. s.charAt() does a simple array look up.
Character.isWhitespace() also does a simple array look up plus some bit
checking, so it's pretty quick.

1 comment:

Javier Aranda said...

If you have a reason to not comply to that rule then disable it. If you google "InefficientEmptyStringCheck" you might find that people such as ActionPMD disregard it. Consider that the performance gain is negligible, for the cost of increased complexity and bytecode size.

I personally have had bitter arguments with managers, trying to convince them not to sabotage the code for the sake of putting off some yellow signs. Long life to metrics over rationale quality ;-).