-5

The object has 6,7 fields. cache.get() is a map read. Which one is faster?

obj temp = cache.get(key);                              // temporary object creation
Int id = temp != null ? temp.getId() : null;

or

Int id = cache.get(key) != null ? cache.get(key).getId() : null;       // cache read twice

For Java with low latency, which of the above is better?

khelwood
  • 55,782
  • 14
  • 81
  • 108
sachyy
  • 532
  • 4
  • 8
  • 2
    Your first one isn't *creating a temporary object*. It's assigning a value to a temporary variable. – khelwood Feb 01 '23 at 10:19
  • 1
    The only thing potentially eating any perfomance here is the `cache.get` - why would you call it twice? – f1sh Feb 01 '23 at 10:29

1 Answers1

2

In the first snippet, you are not creating a temporary reference - you are assigning an existing object to a local variable that will be go out of scope soon.

The first snippet is preferable, although if cache is a simple HashMap it would probably be unnoticeable. It becomes more important if cache is something fancier, e.g., some sort of synchronized map that needs to handle concurrency.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • would there be any cost is assignment, any shallow copy ? – sachyy Feb 01 '23 at 13:19
  • In Java, assigning an object doesn't perform any copying of the data, shallow or otherwise - it's just another reference to the same object. You can think of it as assigning a pointer - the only thing you're copying is the address in memory. – Mureinik Feb 01 '23 at 15:48