I am writing a utility method which can check for empty and null string, or collection or an object or any general types -
public static boolean isEmpty(Object obj) {
if (obj == null)
return true;
if (obj instanceof Collection)
return ((Collection<?>) obj).size() == 0;
// is below line expensive?
final String s = String.valueOf(obj).trim();
return s.length() == 0 || s.equalsIgnoreCase("null");
}
How can I make my above method efficient, since above isEmpty
method will be called multiple times from the application which is very performance critical?
I am suspecting below line will be expensive because of heavy toString methods and it will create temporary garbage as well that might cause GC and slow down the performance?
final String s = String.valueOf(obj).trim();
Update:-
I have separated isEmpty method for each type now. Below is what I got after simplifying the above isEmpty method.
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
return false;
}
public static boolean isEmpty(Collection<?> value) {
if (value == null || value.isEmpty()) {
return true;
}
return false;
}
public static boolean isEmpty(String value) {
if (value == null || value.isEmpty()) {
return true;
}
return false;
}
Update 2:-
If I need to check for map null or empty, should I keep both collection isEmpty and Map isEmpty method both or Collection isEmpty method will be fine for that?
public static void main(String[] args) {
Map<String, String> hello = new HashMap<String, String>();
System.out.println(isEmpty(hello));
Map<String, HashMap<Integer, String>> primary = new HashMap<String, HashMap<Integer, String>>();
System.out.println(isEmpty(primary));
}
public static boolean isEmpty(Collection<?> value) {
return value == null || value.isEmpty();
}
public static boolean isEmpty(Map<?, ?> value) {
return value == null || value.isEmpty();
}