7

There is a method that has some conditional logic and returns an empty String '' (no space) in some cases. Which method is more effective/faster to use in this case: String.isEmpty() or String.isBlank()?

3 Answers 3

19

String.isEmpty is marginally faster (~0.00219ms vs ~0.00206ms, about 6%). This is such a trivially small amount that there's no reason to worry about which one you use from a performance perspective.

Practically speaking, you should generally use String.isBlank if you expect potentially whitespace strings (e.g. from user input that may be all whitespace), and String.isEmpty when checking fields from the database, which will never contain a string of just whitespace.

4
  • I haven't really tested it out, but would agree with such marginal difference, it mostly depends on what you want to validate -- blank vs. empty. Commented Dec 11, 2018 at 15:35
  • 1
    @JayantDas Yeah, a difference this small means about 0.00012ms per use, so you would need millions of uses to make a difference. Commented Dec 11, 2018 at 15:38
  • 1
    Haven't you mixed these two up? isBlank is the one when you expect whitespace strings and not the other way around, and it must be the slower one since it needs to check characters and not just length. Commented Dec 11, 2018 at 16:13
  • @JakeCobb That's what I get for answering before coffee. I just realized i mixed up my variables in the benchmark I was using. One sec... Commented Dec 11, 2018 at 16:29
3

Faster here is very broad to classify, as you will need lot of considerations to test that out. It depends on what is your use case and accordingly which method fits in best.

String.isBlank handles any string even with white space, whereas the same is not true for String.isEmpty. So if you expect empty string ('') always, then using either of them should be fine.

0

String.isEmpty() will be better. Assuming that you are not expecting strings containing just whitespace returning a true value. If you want it to also treat strings containing whitespace as empty use String.isBlank()

The difference between the two is very slight but the docs specify what will be returned depending on input.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.