简体   繁体   中英

Which is more efficient

This is something I thought up for assigning a group of consecutive buttons. I like this style but would it be more efficient to do individual buttons with find by id ?

    for(int i = 0; i < NanoConstants.NUMBER_OF_BUTTONS;i++){ //assign buttons
        Button addButton = (Button) findViewById(getResources().getIdentifier("project_button_" + String.valueOf(i), "id", getPackageName()));
        addButton.setText(getResources().getStringArray(R.array.project_names)[i]);
        addButton.setOnClickListener(this);
        mProjectButtons.add(addButton);
    }

Thanks Everyone !

Since this code appears to run once on application start-up I would avoid trying to micro-optimize it. Stick with the style that makes the code the most readable.

No, it wouldn't be. for loops are just as efficient as the unrolled versions, are much better for readability, and reduce code and complexity.

You can add the buttons in a groupview and looping its childs with getChildAt and check the view if it is a button, like below:

int childCnt = viewGroup.getChildCount();
for(int i=0;i<childCnt;i++){
  View view = viewGroup.getChildAt(i);
  if(view instanceof Button){
    Button button = (Button)view;
    addButton.setText(getResources().getStringArray(R.array.project_names)[i]);
    addButton.setOnClickListener(this);
    mProjectButtons.add(addButton);
  }
}

Even now if you added a button no need to change this code, just add it in the layout and add a value in the array.
But as Elliott Frisch said:

Since this code appears to run once on application start-up I would avoid trying to micro-optimize it. Stick with the style that makes the code the most readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM