# check for null before or after casting

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());


and

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 single best way to know what (if any) performance difference exists is to benchmark it yourself. – RubberDuck Jul 4 '17 at 14:15
• Another approach, in this case, would be to study the resulting bytecode to see how similar they are. – RubberDuck Jul 4 '17 at 14:16
• The bytecode doesn't matter at all. Only the generated machine code matters. – Roland Illig Jul 4 '17 at 21:33
• The first example has no casting at all. Therefore, if you happen to get a Kitten or something weird like that, it'll just print a stringified version of it using Object#toString(). This may or may not be what you want. – ndm13 Jul 10 '17 at 0:35

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.