-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?

2
  • 2
    Your first one isn't creating a temporary object. It's assigning a value to a temporary variable. Commented Feb 1, 2023 at 10:19
  • 1
    The only thing potentially eating any perfomance here is the cache.get - why would you call it twice? Commented Feb 1, 2023 at 10:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

would there be any cost is assignment, any shallow copy ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.