0

I use the following code to check timing:

public static void main(String[] args) throws Exception {
    String foo = "foo";
    long start=System.currentTimeMillis();
    if (StringUtils.isBlank(foo));
    long end=System.currentTimeMillis();
    System.out.println("isBlank="+(end-start));
    start=System.currentTimeMillis();
    if (foo!=null && !foo.isEmpty());
    end=System.currentTimeMillis();
    System.out.println("Sec="+(end-start));
}

The StringUtils.isBlank() method takes 3ms longer than a simple String.isEmpty() method. Which method should we use?

grebulon
  • 7,697
  • 5
  • 42
  • 66
kartavya soni
  • 91
  • 1
  • 8

1 Answers1

7
StringUtils.isBlank(foo));

Checks if a String is whitespace, empty ("") or null.

StringUtils.isBlank()

foo.isEmpty()

Returns true if, and only if, length() is 0.

isEmpty()

So if want something advanced like which will not throw NPE if string is null, ignore the empty string (so auto trim ) then use StringUtils.isBlank(foo));

On the other hand as you shown the performance difference which have a very good cause to be isEmpty() just see the length.

Its your choice depending on the need.

Saif
  • 6,804
  • 8
  • 40
  • 61