简体   繁体   中英

The fastest way to get the LayoutInflater

I can get the LayoutInflater with:

inflater = LayoutInflater.from(context);

or

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

Which way is faster and recommended?

The second version will be (marginally) faster, as the first version involves a method lookup (see code below). For the sake of clarity/maintainability the first version is preferable.

    /**
     * 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;
    }

Reference: LayoutInflator.java

I do not have the answer to this question but i can suggest a way to find out. You should profile these methods and see for yourself which one is fastest in execution.

You could do this:

long startTime = System.nanoTime();
inflater = LayoutInflater.from(context);
long endTime = System.nanoTime();
long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds.

Run it a few time and write down or save the returned time and then run the other function to see wich one preforms fastest

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.

Now you know how to profile any method you want, to see which one is faster in execution!

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