1

This is a general coding style question regarding which style is more general or elegant.

When reading Java collection source code, I found the first style more frequently than the second one. Could anyone shred some light/ reasoning on this? IMHO, the second style is more concise than the first one, but actually, the first one should be redeemed more elegant in some way I cannot argue.

  1. creating local variable.
private Set<K> keySet;

public Set<K> keySet() {
    Set<K> ks = keySet;
    if (ks == null) {
        ks = new KeySet();
        keySet = ks;
    }
    return ks;
}

  1. operating on class member variable.
public Set<K> keySet() {
    if (keySet == null) {
        keySet = new KeySet();
    }
    return keySet;
}
3
  • Which version of the source code are you looking at? All I can find is return (ks = keySet) == null ? (keySet = new KeySet()) : ks;. No second assignment to ks. Commented Sep 25, 2019 at 5:04
  • The version of source code does not matter. For your mentioned source code, why not writing it as: if(keySet == null) keySet = new KeySet(); return keySet; Commented Sep 25, 2019 at 8:37
  • @lucas The version of the source code does matter if you can't produce a version of the source code that actually contains what you allege it contains. Commented Sep 26, 2019 at 10:43

1 Answer 1

3

It's an attempt at micro-optimizing lazy initialization.

Since collection classes are used frequently, including in situations where high throughput is needed, the goal is to save as much time as possible.


The optimization attempted here is to lower the amount of getfield operations.

Since the set is only initialized once, we are worried about performance after initialization.

The 1st code block avoids a getfield by ensuring the check for null is local. After the set has been initialized, the 1st code block will always result in one getfield call, while the 2nd code block will always result in two getfield calls.

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

1 Comment

Great point, I guess this is the answer I am looking for. Great Thanks. @Vince Emigh > JIT may optimize this. Eg, don't expect this optimization on Dalvik. Pulling a field into a local can be useful for other reasons, such as a null check for a field that could be accessed concurrently. – NateS Nov 22 '12 at 3:07

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.