2
\$\begingroup\$

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ The single best way to know what (if any) performance difference exists is to benchmark it yourself. \$\endgroup\$ – RubberDuck Jul 4 '17 at 14:15
  • 1
    \$\begingroup\$ Another approach, in this case, would be to study the resulting bytecode to see how similar they are. \$\endgroup\$ – RubberDuck Jul 4 '17 at 14:16
  • \$\begingroup\$ The bytecode doesn't matter at all. Only the generated machine code matters. \$\endgroup\$ – Roland Illig Jul 4 '17 at 21:33
  • \$\begingroup\$ 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. \$\endgroup\$ – ndm13 Jul 10 '17 at 0:35
2
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.