获取LayoutInflater的最快方法

3

我可以通过以下方式获取LayoutInflater:

inflater = LayoutInflater.from(context);

或者

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

哪种方式更快且更受推荐?

你可以通过计时来轻松地找出哪个更快。 - tyczj
你打算获取多少次新的 LayoutInflater 才会有所影响呢?顺便说一下,这里建议使用第二种方法。 - ci_
2个回答

2
第二个版本会(稍微)更快,因为第一个版本涉及到方法查找(请参见下面的代码)。为了清晰和可维护性,第一个版本更可取。
    /**
     * Obtains the LayoutInflater from the given context.
     */
    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

参考:LayoutInflator.java


1
我没有这个问题的答案,但我可以建议一种找到答案的方法。您应该对这些方法进行分析,自己判断哪种执行速度最快。
您可以这样做:
long startTime = System.nanoTime();
inflater = LayoutInflater.from(context);
long endTime = System.nanoTime();
long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.

运行几次并记录返回的时间,然后运行另一个函数以查看哪个执行速度更快。
long startTime = System.nanoTime();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
long endTime = System.nanoTime();
long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.

现在你知道如何分析任何想要的方法,以查看哪个执行速度更快!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接