Reputation: 2662
Is there any performance difference between layouts done in code vs XML layouts in android?
Upvotes: 3
Views: 1326
Reputation: 12674
Its hard to imagine that using XML would ever be faster.
Android SDK has a lot of performance tweaks to make loading and parsing XML fast. in recent times, if you use data binding to replace findViewById this dramatically improves performance as well as each call to findViewById parses the XML tree. Where as databasing will only parse the tree once.
Also, using include in XML allows for reuse of Views which improves performance especially in cases where you would have large object churn. There is all sorts of I eternal caching and pooling of objects as well so it's possible that inflated objects are cached/pooled and cloned for subsequent use reducing the overhead on using XML. I know this is definitely the case for Drawable assets hence the need to call mutate if you ever plan on modifying one.
There are scenarios where code would be slower, with every View you create and add to your layout, you will trigger a measure and layout pass, so if you try to build a complex, deep nested layout using code at runtime, this would take a lot longer to load.
There are other factors to consider, like:
If the ViewGroup you want to create is simple, or simply want to create a single View and insert it into a ViewGroup, doing it in code is probably hard to beat by any criteria.
If you want to do something a lot more complex, using XML and all its features like ViewStub, includes, DataBinding is probably the way to go. I have noticed that inflating Views can be visibly slow, if you do it a lot, hence the ViewHolder pattern, but if you're careful, it's hard to justify ever building Views and ViewGroups in code for any thing but simple layout additions.
Upvotes: 0
Reputation: 1850
Yes. XML layouts need to be loaded, parsed and inflated to generate the View. Behind the scenes the LayoutInflater
does exactly what you would do when writing layouts through code, but with the overhead mentioned before.
Here is an interesting article on this topic, which covers View generation through code, also it is about a library written in Kotlin
: https://nethergrim.github.io/performance/2016/04/16/anko.html
But even though there is a performance win, I would not recommend to write layout in code for the following reasons.
AppCompatDelegate
(loading Views for the latest Androind version. E.g. an AppCompatButton
instead of a normal Button
.Upvotes: 2
Reputation: 18489
As far as i know, i can make one difference. Please correct/enhance my answer if possible.
Upvotes: 1