Use findViewById in all scopes or use a variable?

Asked

Viewed 104 times

0

Which of the most recommended strategies for a good application performance? Using findViewById whenever we use some element of View or to do so only once by assigning to a variable?

example in Xamarin.Android:

public class MainActivity : Activity 
{

  private EditText _CampoNome;

  protected override void OnCreate(Bundle savedInstanceState)
  {
     ...

     _CampoNome = FindViewById<EditText>(Resource.Id.edtCampoNome);
     _CampoNome.Text = "ola mundo";

     EscreverNome(); 
  }

  private void EscreverNome()
  {
      Console.WriteLine(_CampoNome.Text);
  } 
}

or

public class MainActivity : Activity 
{
  protected override void OnCreate(Bundle savedInstanceState)
  {
     ...

     FindViewById<EditText>(Resource.Id.edtCampoNome).Text = "ola mundo";

     EscreverNome(); 
  }

  private void EscreverNome()
  {
      Console.WriteLine(FindViewById<EditText>(Resource.Id.edtCampoNome).Text);
  } 
}
  • 1

    I particularly if I will use in various situations and again and again I prefer to create a variable, to avoid processing and reduce memory allocation, instantiated at once rather than instantiating about 500 times

1 answer

1

The transactions carried out by the method findViewById may be considered costly, but they do not usually affect performance significantly outside of lists or loops. It is recommended that you use the standard whenever possible ViewHolder in lists, so the recycling of views greatly improves the performance of the app.

As Gabriel commented, it’s more efficient that you save the View reference to a variable if you want to use it at different times of the life cycle.

In the case of layouts with many sublevels, you can save some processing by calling the method findViewById at a lower level of the layout tree.

I suggest reading this reply (in English) on the same subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.