0

I have two pieces of code like below:

code 1:

Optional.fromNullable(integerVsLongMap.get(id)).or(getDefaultLong());

and

code 2:

integerVsLongMap.contains(id) ? integerVsLongMap.get(id) : getDefaultLong();

I would like to know which piece of code is more efficient and preferable in terms of space and time complexity and in terms of coding practices, cause what I see is both do the same thing?

4
  • 1
    not a direct answer: have you thought of microbenchmarking this ? Besides that (in my opinion): code variant 2 doesn't look nice. Commented Jan 11, 2016 at 11:35
  • @Marged Not a direct answer? Maybe you meant "question"? Anyway, what's indirect here? Commented Jan 11, 2016 at 11:36
  • 1
    If using Java 7 or earlier, is there a restriction of non-null values in integerVsLongMap? If not, (2) is the only correct way to do it, since there may be a null value in the map. Correctness should trump efficiency and readability. If using Java 8, use Map.getOrDefault. Commented Jan 11, 2016 at 11:38
  • I wanted to say that my comment/answer is not directly that kind of reply that fully answers your question. That's all. Commented Jan 11, 2016 at 11:46

2 Answers 2

6

The best, both in terms of performance and readability, would be to use

Long v = integerVsLongMap.getOrDefault(id, getDefaultLong())

in my opinion.

Performance is probably not a concern, but it can nevertheless be improved for both solutions:

  • the first one creates an Optional instance every time
  • the second one makes two map lookups when one is sufficient

The time complexity of all solutions is the one of the map lookup (O(1) for a HashMap, O(log(n)) for a TreeMap, for example).

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

1 Comment

He's not talking about performance but space and time complexity (I guess using Big-O notation), but yes that's also (or even more) important.
1

Space and time complexity are always O(1), not depending on the size of the map. But if you look at real space and time needed

Long v = integerVsLongMap.getOrDefault(id, getDefaultLong())

and

integerVsLongMap.contains(id) ? integerVsLongMap.get(id) : getDefaultLong();

are the best solutions because don't creates new objects.

Internally the getOrDefault do exactly what the second code does. Here the code of getOrDefault

public V getOrDefault(Object key, V defaultValue) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

Creating an Optional needs to create always a new Object.

If you need to use the returned value in a chain the best solution is with the Optional.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.