-1

I read that you should avoid referencing a field too often in a method and instead just do it once, assigning it to a local variable, e.g.:

public static void doSomething() {
    final Map<String, Integer> myMap = this.theMap;
    //do some processing with myMap
}

The reason being efficiency, it just takes longer to access the field every time. Is that something you should worry about?

Karthikeyan KR
  • 1,134
  • 1
  • 17
  • 38
Roland
  • 7,525
  • 13
  • 61
  • 124
  • 3
    Do you have a source for this claim? – aUserHimself Mar 16 '17 at 12:08
  • 2
    No, don't worry about it. "Premature optimization is the root of all evil" -- DonaldKnuth – Harald Gliebe Mar 16 '17 at 12:14
  • 1
    The answer is: **No**, you should not worry about this. But instead of downvoting, closing as a duplicate of http://stackoverflow.com/q/20750020/3182664 would be more appropriate. And that the *core* of the question is **reasonable and valid** can be seen in another example: http://stackoverflow.com/q/7943763/3182664 The implementors of the JDK are doing this (for several reasons, one of them being a bordercase (!) of performance optimization) – Marco13 Mar 16 '17 at 12:26

2 Answers2

0

This is absolutely wrong.

It makes no difference at all how the variable is accessed (locally or using the class' member). In the end both fields will just contain a reference to the very same location in the memory without any impact to performance. Even when using a getter for your class' field it will make no difference as the JIT compiler will inline the method call once it noticed that this might improve performance.

dpr
  • 10,591
  • 3
  • 41
  • 71
0

Optimisationwise: it does nothing really. Any benefit if any would also be provided by an optimizer.

Only benefit is for you, the coder, by being able to name it differently so you know it's purpose in the method better.

public function test() {
    Produce harvestedFruits = this.produce;
    for(Produce fruit : harvestedFruits ) {
       if(fruit.isRotten()) {
             harvestFruits.remove(fruit);
       }
    }
}

And even then, I'd advice using getter and setter methods, so extended functions can do their own thing and testing becomes easier, and with documentation you provide nice highlights when hovering over the method in an relatively advanced IDE

  Produce fruit = this.getProduce();
Tschallacka
  • 27,901
  • 14
  • 88
  • 133