2

There is method, that have some condition flow and returning empty String ''(no space) in some case. Which method is more effective/faster to use in this case: String.isEmpty() or String.isBlack()?

7

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.

  • 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. – Jayant Das Dec 11 '18 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. – sfdcfox Dec 11 '18 at 15:38
  • 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. – Jake Cobb Dec 11 '18 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... – sfdcfox Dec 11 '18 at 16:29
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.