ZakTaccardi
ZakTaccardi

Reputation: 12477

What's more efficient? Storing variable references vs not (Context in Android)

Let's say we are in the middle of a method. And I have a choice between two styles of programming.

Option A: use getContext().getResources() every time I need to access resources

public void doSomeStuffA(){
  //...
  getContext().getResources().getDrawable(R.drawable.ic_launcher);
  getContext().getResources().getDrawable(R.drawable.ic_arrow);      //...
}

Option B: Store getContext().getResources() in a variable.

public void doSomeStuffB(){
  //...
  Resources r = getContext().getResources();
  r.getDrawable(R.drawable.ic_launcher);
  r.getDrawable(R.drawable.ic_arrow);
  //...
}

Which style is better?

Upvotes: 2

Views: 422

Answers (3)

Vivin
Vivin

Reputation: 1367

As a general practice (Not in particular this case)

Use Option A:

  • Resources keep on changing and you want the most recent value of resource.

  • If you are calling methods on resource just once.

Use Option B:

  • Resources don't change then you can use a reference and use it wherever you want.

Upvotes: 1

Leonidos
Leonidos

Reputation: 10518

Use Kotlin to make everything neat and clean )

fun someFun() {
    with(getContext()) {
        var d1 = getDrawable(R.drawable.ic1)
        val d2 = getDrawable(R.drawable.ic2)
        ...
    }
}

Upvotes: 0

pojo-guy
pojo-guy

Reputation: 979

Like so much in performance and tuning, the correct answer is "it depends". 99 percent of the time, the difference between an extra hashmap dereference versus a variable reference is not the biggest (or even noticable) performance issue. The trick is to understand when it is likely to be an issue (frequent calls in tight loops for example).

Within a single method, I would tend to use option B primarily for readability.

Upvotes: 3

Related Questions