0

I'm dealing with an API that returns Object when I ask for a property.

Object x = r.getProperty("id");

But I know for a fact that this property in particular is a Long. So these are the two options I'm weighing:

Long x = Long.parseLong(r.getProperty("id").toString());

Long x = (Long)r.getProperty("id");

Which one is preferred performance-wise?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
David Perez
  • 478
  • 5
  • 17
  • Based on gut instinct alone - probably the second one. One fewer object to allocate space for and construct. – Mshnik Dec 19 '16 at 20:04
  • 2
    Why would converting it to string and then converting it back to long have better performance than just casting it to long – Natecat Dec 19 '16 at 20:05
  • I though the same but I have always heard that casts are very expensive – David Perez Dec 19 '16 at 20:07
  • This question discusses two specific alternatives, only one of which is a cast. The duplicate does not look like a good fit; voting to re-open. – Sergey Kalinichenko Dec 19 '16 at 20:10
  • 2
    What you heard about casts being expensive is a myth as far as modern Java engines are concerned. There is very little performance penalty to downcasting (and none whatever to upcasting--e.g., from `String` to `Object`). – Ted Hopp Dec 19 '16 at 20:10
  • 1
    What you heard about casts is nonsense. If the object already is a Long there is practically nothing to do except check that. – user207421 Dec 19 '16 at 20:31

2 Answers2

3

If you know for a fact that it's a Long, I'd definitely go with the cast. It's clearer and probably more efficient. If you're sure the return type is a Number, you can call Number.longValue(). If that's not either a certainty, then I might go with the parsing option to be safe and avoid the instanceof boilerplate.

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Agreed, and I'm assuming casting would be quite a bit faster, although the speed of this operation probably doesn't have any actual influence on performance, unless your program has no IO at all. – Klaus Groenbaek Dec 19 '16 at 20:07
  • Yeah, this question was more about curiosity than anything... the IO for sure is the slowest part of the program. – David Perez Dec 19 '16 at 20:17
1

The second approach is faster, but it is not very forgiving: unless the value is actually a Long, the code is going to crash.

The first approach, on the other hand, will survive a change of type: if you later decide to use Integer, String, Byte, or some other type with a custom toString that prints a numeric value compatible with long, the code is going to work. Hence, the first approach is more robust.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523