In Java is there a performance difference between referencing a field through getter versus through a variable?

后端 未结 9 1258
失恋的感觉
失恋的感觉 2020-12-20 17:49

Is there any differences between doing

Field field = something.getSomethingElse().getField();
if (field == 0) {
//do something    
}
somelist.add(field);
         


        
9条回答
  •  -上瘾入骨i
    2020-12-20 18:23

    If the method is a simple getter with no processing involved it isn't an issue. If it involves extensive calculation, a property wouldn't do what you want anyway.

    The only time I'd worry about any difference is in a tight loop with a huge number of iterations (many thousands). Even then this is probably only an issue if you're using aspects to weave extra processing (e.g. logging), this can involve creating thousands of extra objects (e.g. JoinPoints and parameter autoboxing) and resultant GC issues.

提交回复
热议问题