Thursday, September 23, 2010

Returning empty collection or a null?

Should a null value for an expected collection be preferred or an empty Collection object? Lets see through a program:


import java.util.Collection;
import java.util.Vector;

import static java.lang.System.out;

public class E {

public void isNull (Collection col) {
long t = System.nanoTime();
if (col == null) {
}
out.println ("Time to check null: " + (System.nanoTime () - t));
}

public void isEmpty (Collection col) {
long t = System.nanoTime ();
if (col.isEmpty ()) {
}
out.println ("Time to check empty: " + (System.nanoTime () - t));
}

public static void main (String args []) {
E e = new E ();
e.isNull ((Collection) null);
e.isEmpty (new Vector ());
}

}
Running this on my laptop with Java 6 produced:
Time to check null:  45234
Time to check empty: 10750

Something to think about..

No comments: