Marcel Bro
Marcel Bro

Reputation: 5025

Getting context from getContext() or from constructor as a field

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)?

Upvotes: 2

Views: 2930

Answers (3)

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

Instead of using getContext() every where, it is better to pass current context as argument in constructor where you wanna to use.

Upvotes: 4

zapl
zapl

Reputation: 63955

View#getContext() is

class View {
    protected Context mContext;
    public final Context getContext() {
        return mContext;
    }
}

and a locally cached implementation:

class X {
    private final Context mLocalContext;
    public X(Context ctx) {
        mLocalContext = ctx;
    }
}

Now there is a very small difference when you use mLocalContext instead of getContext(). 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 since View#mContext is mutable (can change). In the local example it can assume that mLocalContext can'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 a new Context() or so).

Upvotes: 1

MikeHelland
MikeHelland

Reputation: 1159

It looks like, from the source code, the View's constructor stores the context parameter and that's what getContext() returns:

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/view/View.java#View.getContext%28%29

So, my instinct would be that storing the parameter yourself would be redundant, since the super class is already doing it for you.

Upvotes: 1

Related Questions