Android UI: XML vs Dynamic Views

Abduaziz Kayumov
3 min readJun 4, 2018

Android App UI is usually built using XML markup language. Android Studio has a nice preview and many other extra plugins that work around XML. However, there are some apps that are fully written without XML by creating views dynamically. Telegram app is one of them. Because I am working on a similar app like Telegram, I feel interested in how fast Telegram app opens from a cold start comparing to similar app I am building. During my tests, my app with almost the same UI elements with Telegram performed about 6–7 times slower. Now I have a challenge to win the race, so I decided to test dynamically created views vs XML inflation.

Here are some pre-conditions before the test:
1. There is only one MainActivity with NoActionBar style for both methods.
2. Both methods (XMS vs Dynamic UI) will have one FrameLayout as a parent.
3. 5 tests will be conducted, each will add some number of TextView to the parent layout.
4. Both methods will be tested on the same device: Xiaomi Mi A1 (Android 8.0)
5. MainActivity has hardwareAccelerated option enabled.
6. On each test, test app will be opened 5 times to get better milliseconds.

To achieve fair results, I wait some minutes after each test, so that app always starts from a cold start. I used Android Studio Activity Manager logs to catch exact milliseconds:

TEST #1

App opened 5 times in both methods. One parent FrameLayout and 100 TextViews are created dynamically and using XML.

TEST #2

One parent FrameLayout and 500 TextViews are created dynamically and using XML.

TEST #3

One parent FrameLayout and 2500 TextViews are created dynamically and using XML.

TEST #4

One parent FrameLayout and 15,000 TextViews are created dynamically and using XML. Android Studio’s XML layout preview is no longer working. I needed to edit the layout file with a text editor. :- )

TEST #5

One parent FrameLayout and 60,000 TextViews are created dynamically and using XML. App opened 3 times for each methods.

Conclusion

As you can see from above results building UI dynamically performs better as view count increases:

It is clear from the chart that building UI dynamically is about 5 times faster than XML inflated UIs. Would you create views dynamically because of its speed or still prefer XML? Let me know.

Here are the MainActivity and layout file:
MainActivity.kt
activity_main.xml

--

--