Search code examples
androidfindviewbyid

Use "findViewById" repetitively or store View?


Being the efficiency freak that I am (as I'm sure lots of you all are as well), I've wondered this for a while and just thought of posing this question:

Two scenarios, possibly two different answers.

If I'm looping through a list of items and updating a bunch of EditTexts in a LinearLayout as such, what are the pros/cons of these two methods: 1)

for (int i = 0; i < itemList.size(); i++) {
    ((TextView)findViewById(itemList.get(i).getId())).setText(itemList.getText());
    ((TextView)findViewById(itemList.get(i).getId())).setColor(itemList.getColor());
}

2)

TextView tv;
for (int i = 0; i < itemList.size(); i++) {
    tv = ((TextView)findViewById(itemList.get(i).getId()));
    tv.setText(itemList.getText());
    tv.setColor(itemList.getColor());
}

I think the underlying question is how efficient is "findViewById"? This may be picky, I think 2) is the better solution. Thanks!


Solution

  • This is not picky at all. 2nd option is without doubt the better one.

    1

    for (int i = 0; i < itemList.size(); i++) {
        ((TextView)findViewById(itemList.get(i).getId())).setText(itemList.getText());
        ((TextView)findViewById(itemList.get(i).getId())).setColor(itemList.getColor());
    }
    

    Looks clean, but isn't. If you are working with one and the same textview, absolutely do not call findViewById more than once.

    2

    TextView tv;
    for (int i = 0; i < itemList.size(); i++) {
        tv = ((TextView)findViewById(itemList.get(i).getId()));
        tv.setText(itemList.getText());
        tv.setColor(itemList.getColor());
    }
    

    This is the better option, because it only calls findViewById once. It's a little less readable, though.

    You could also consider a 3rd option

    for (int i = 0; i < itemList.size(); i++) {
        TextView tv = ((TextView)findViewById(itemList.get(i).getId()));
        tv.setText(itemList.getText());
        tv.setColor(itemList.getColor());
    }
    

    This keeps everything in the loop (easier to read, imo) without notably sacrificing efficiency. I prefer the 3rd, but the 2nd is a good pick as well.