Let’s use custom or extending View as an example.
Is it more effective to save Context parameter from constructor as a field, than calling getContext() everywhere (supposing there are, let’s say, 10 or more places where it is needed)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
View#getContext()isand a locally cached implementation:
Now there is a very small difference when you use
mLocalContextinstead ofgetContext(). The JVM can get to the required reference of the context object without having to execute the method (which takes a tiny bit of extra time). That call can’t be optimized away sinceView#mContextis mutable (can change). In the local example it can assume thatmLocalContextcan’t change and optimize the code a little better. [Note: I am not 100% sure about what optimizations are / can be done]The difference might be measurable if you use the context a lot but in this case it does not matter much. It’s still a good idea to cache Objects locally if you need them often. Especially when their (re)construction takes time (e.g. when
getContext()would create anew Context()or so).