【问题标题】:[Android preformance]:Shoud i findViewById every time i need it or make it a field variable [duplicate][Android preformance]:Shoud i findViewById every time i need it or make it a field variable [duplicate]
【发布时间】:2016-12-18 18:22:17
【问题描述】:

什么对内存管理和性能更好? 在需要时调用该元素,或者如果需要多次调用该元素,请将其设为字段变量 例如:

 private void setNumber(int intNumber) {
        TextView number = (TextView) activity.findViewById(R.id.number);

        String numberString = "#" + String.valueOf(intNumber);
        number.setText(numberString);
        number.animate().alpha(1f).setDuration(1000).start();
        number = null;

    }

在此函数中,每次调用该函数时,元素 number 由其 id 调用,但这样做可能过于昂贵,并且不能弥补这样一个事实,即虽然不需要内存,但不会释放内存并执行这样更好。

class{
    TextView number;

    constructor{

    number = (TextView) activity.findViewById(R.id.number);

    }

private void setNumber(int intNumber) {

    String numberString = "#" + String.valueOf(intNumber);
    number.setText(numberString);
    number.animate().alpha(1f).setDuration(1000).start();
    number = null;

    }
}

幻灯片说明:大约每 60 秒需要此元素

【问题讨论】:

  • 使用第二个选项更好
  • 你不能使用它,只需要使用像 ButterKnife 这样的 View Injection 库来为你处理它
  • 变量。 FindViewById 是 O(n) 遍历视图。这就是为什么在列表视图适配器中使用视图持有者 - 以避免每次绑定视图时 O(n) 遍历。我会投票反对像黄油刀这样的东西,只要你有魔术注释为你做事,你的代码就会变得不那么可读和可维护。
  • ButterKnife 只是一个额外的库负担,只是一个花哨的东西,它与findviewbyid 几乎相同,完全同意@GabeSechan

标签: android performance android-layout


【解决方案1】:

我强烈建议您查看此帖子Efficiency of findViewById

因为调用 findviewbyid 会消耗大量性能,所以您是否有很多要操作的视图。

【讨论】:

    猜你喜欢
    • 2022-11-09
    • 2012-06-19
    • 1970-01-01
    • 2022-12-01
    • 2019-10-05
    • 2023-01-15
    • 2022-08-17
    • 2022-12-02
    • 2023-01-06
    相关资源
    最近更新 更多