check for null before or after casting

Posted on


I have a list of BasicDBObject that I fetch from my database. This is basically a JSON document converted into a java Object.

Let’s assume that we have a BasicDBObject named result

This JSON document may or may not contain the key name. If the document doesn’t contain the key, result.get("name") will return null.

Is there a difference in terms of performance between this :

BasicDBObject result = ...
Object name = result.get("name"); 
String nameString = (name == null ? "." : name.toString()); 


BasicDBObject result = ...
String name = (String) result.get("name"); 
String nameString = (name == null ? "." : name);

Even if this part of the code is called 100 000+ times within a function, I know this wil never be the bottleneck, I’m just interested in the answer.


The first snippet runs on any type returned by result.get, the second snippet needs the method to return a String. So it makes only sense to compare the snippets if result.get returns a String. I assume so.

The type cast is a noOp in byte code. So the real difference is that the first snippet calls name.toString(), but the second uses name directly. The result is the same but the method call may be slower than the direct access to name.

If the first is really slower depends on the optimizing that will be done by the compiler and runtime environment. You should benchmark it with the version of java currently in use, if you are interested in the result.

Leave a Reply

Your email address will not be published. Required fields are marked *