【问题标题】:The fastest way to get the LayoutInflater获取 LayoutInflater 的最快方法
【发布时间】:2015-10-07 13:43:19
【问题描述】:
我可以通过以下方式获得 LayoutInflater:
inflater = LayoutInflater.from(context);
或
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
哪种方式更快且值得推荐?
【问题讨论】:
-
-
您打算获得多少次新的LayoutInflater 这很重要? FWIW This 说使用第二种方法。
标签:
java
android
layout-inflater
【解决方案1】:
第二个版本将(稍微)更快,因为第一个版本涉及方法查找(参见下面的代码)。为了清晰/可维护性,第一个版本更可取。
/**
* 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
【解决方案2】:
我没有这个问题的答案,但我可以建议一种方法来找出答案。您应该对这些方法进行概要分析,并亲自查看哪个执行速度最快。
你可以这样做:
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.
现在您知道如何分析您想要的任何方法,看看哪个执行速度更快!