Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access same property (member of object) multiple times in code

Pretty simple question, I have an object (say Obj) which has member variable (say "var"). In one function I need to access this property multiple times (4 to 5 times). What I am doing right now is everytime I do Obj.var to get the value. Is is right (from optimization point of view) to do that or I should store Obj.var in a temporary variable and then use this variable? I am looking for explanation from "how both approaches impact performance" point of view.

=====

What if Obj.var is replaced by Obj.getVar(), a getter method for that variable? How will it impact the performance?

like image 810
Rajvidya Chandele Avatar asked Oct 27 '25 08:10

Rajvidya Chandele


1 Answers

Unless the variable is volatile, the JITC is free to do whatever it wants as long as it can prove that you're not overwriting the field in the meantime (without volatile, it doesn't care about what other threads do).

If you use no local variable, it will do it for you. It could also do it the other way, but I can hardly imagine any case when it makes sense (it could, when you run out of registers).

So it doesn't matter for performance(*), but for readability, the local is nearly always better, so go for it.


(*) On Android, the situation may differ as it's not as smart as server class JVM.

like image 102
maaartinus Avatar answered Oct 30 '25 15:10

maaartinus