Straight-forward language agnostic question. I’ve always done this:
myVar = myObj.myAttribute
when I need to access myAttribute a lot.
I’m wondering if this is just a superstition I’ve acquired, or if it’s generally faster?
Edit: I would also like to know if this
myVar = myObj.myAttribute/100
for (i=0; i<100; i++) {
print myVar*i;
}
is more efficient than putting (myObj.myAttribute/100) in the loop. Will modern compilers and interpreters detect that that part of the equation doesn’t vary?
In this particular case what you did is more efficient, since it’s one division vs 100.
I do property assign to variables only if I can optimize the operations done later, like in your case or expect multiple calls to the same property and the object lookup is likely to be expensive. Generally using local variable should be the more cpu wize way, since it can be costly to do complex property lookups, along with the better control of that property value and possible pre-validation before looping. That said it may be inefficient only if the lookup is likely to occur once or twice for the function call, thus adding overhead and making the code harder to follow up.