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
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– Jayant Das2018-12-11 15:35:51 +00:00Commented 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.sfdcfox– sfdcfox2018-12-11 15:38:53 +00:00Commented Dec 11, 2018 at 15:38
- 1Haven't you mixed these two up?
isBlankis 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– Jake Cobb2018-12-11 16:13:23 +00:00Commented 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...sfdcfox– sfdcfox2018-12-11 16:29:58 +00:00Commented Dec 11, 2018 at 16:29
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.
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.