2

I'm writing a lot of components in Adobe CQ so have to deal a lot with user set properties. And i'm getting a little tired of all the null checks before I can do an isEmpty check.

I'd like to do something like.

"".equals(string);

This would be a lot more readable, but how would it compare performance wise. And yes i would expect to create the "" as a constant if there where multiple checks.

Thanks D

DamianM
  • 21
  • 2

3 Answers3

1

It is preferred to use the isEmpty() method(Simpler and faster source code ). Another efficient way to check empty string in java is to use:

string.length() == 0;
Pol
  • 27
  • 7
1

Personally I use Apache's StringUtils, eg:

if (StringUtils.isEmpty(someString)) {
    ...

or

if (StringUtils.isNotEmpty(someString)) {
    ...

Also I really wouldn't worry about the performance of this unless you have benchmarked an identified it as an issue

beresfordt
  • 5,088
  • 10
  • 35
  • 43
  • 1
    Yeah, adding a 3rd party library to call a single method, is really a big win. And `StringUtils.isEmpty(someString)` looks so much better than `someString.isEmpty()`… – Holger Jul 21 '15 at 08:49
  • I have never worked on a project where there has not been extensive use of apache.commons.lang3; there is a lot of useful stuff in there – beresfordt Jul 21 '15 at 09:06
  • of course. If you add that library as soon as you find a method which does the same as an existing JRE method, you won’t have any project without it. And not to forget, the useful constants: `StringUtils.EMPTY`; no more need to type `""` all the time… – Holger Jul 21 '15 at 09:15
  • `StringUtils.isEmpty` is actually a `null` or empty check. So on the surface `someString.isEmpty()` works until there is any possibility that `someString == null` – Cameron Hotchkies Dec 10 '15 at 23:03
0

You should not care about performance here. Both version have similar speed. Even if they compile differently, JITted code will unlikely to differ more than several CPU cycles (especially given the fact that String.equals is JVM intrinsic). Not the thing you should worry about when programming on Java.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • I think the String.equals is the easiest to read which is the biggest win for me. And if the performance is around the same i'll argue my case if it get brought up in the code review. Thanks for the input. – DamianM Jul 21 '15 at 14:02