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;
}
lucas
  • 2,756
  • 19
  • 15
  • 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`. – user207421 Sep 25 '19 at 05: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;` – lucas Sep 25 '19 at 08: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. – user207421 Sep 26 '19 at 10:43

1 Answers1

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.

Vince
  • 14,470
  • 7
  • 39
  • 84
  • 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 – lucas Sep 29 '19 at 14:33