Use findViewById in all scopes or use a variable?

0

Which of the following strategies is best suited for good application performance? Use findViewById whenever we use any element of View or do it 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);
  } 
}
    
asked by anonymous 28.11.2017 / 13:08

1 answer

1

Operations performed by the findViewById method can be considered costly, but do not usually affect performance significantly outside lists or loops. It is recommended that you use the ViewHolder pattern in lists whenever possible, so refreshing views greatly improves app performance.

As Gabriel commented, it is more efficient that you save the View reference in a variable if you want to use it at different times in the lifecycle.

For layouts with many sub-levels, you can save some rendering by calling the findViewById method at a lower level of the layout tree.

I suggest reading this answer on the same topic.

    
28.11.2017 / 14:31