<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abhishek Luthra on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Luthra on Medium]]></description>
        <link>https://medium.com/@er-abhishek-luthra?source=rss-8e808d26f4c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZXDXuvVv2Au3rwGWc-PgIA.jpeg</url>
            <title>Stories by Abhishek Luthra on Medium</title>
            <link>https://medium.com/@er-abhishek-luthra?source=rss-8e808d26f4c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:06:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@er-abhishek-luthra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding the Dependency Inversion Principle: Building Flexible and Maintainable Software]]></title>
            <link>https://er-abhishek-luthra.medium.com/understanding-the-dependency-inversion-principle-building-flexible-and-maintainable-software-fa32d117ff4c?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa32d117ff4c</guid>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 08:27:47 GMT</pubDate>
            <atom:updated>2024-07-06T08:27:47.150Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of software design is filled with principles and patterns that guide developers in creating robust and maintainable applications. One such fundamental principle is the Dependency Inversion Principle (DIP). Despite its importance, DIP often confuses many, partly due to its name. In this article, we’ll demystify the Dependency Inversion Principle using clear explanations, relatable analogies, and we’ll also explain why it is called Dependency Inversion.</p><h3>What is the Dependency Inversion Principle?</h3><p>The Dependency Inversion Principle is one of the five SOLID principles of object-oriented design, formulated by Robert C. Martin (Uncle Bob). It states:</p><ol><li><strong>High-level modules should not depend on low-level modules. Both should depend on abstractions.</strong></li><li><strong>Abstractions should not depend on details. Details should depend on abstractions.</strong></li></ol><p>In simpler terms, it means that high-level components of your application (like business logic) should not be directly dependent on low-level components (like data access). Instead, both should rely on interfaces or abstract classes. This principle helps in achieving loose coupling, making the system more flexible and easier to maintain.</p><h3>Why is it Called Dependency Inversion?</h3><p>The term “Dependency Inversion” might sound complex, but it’s quite logical once you break it down. The “inversion” part of DIP comes from the way it flips the traditional dependency direction.</p><h3>Traditional Dependency Direction</h3><p>In traditional software design, high-level modules depend on low-level modules. This is a straightforward dependency flow where higher-level functionalities rely on the implementation details of lower-level components.</p><ul><li><strong>High-Level Module</strong> (e.g., Business Logic) → <strong>Low-Level Module</strong> (e.g., Database Service)</li></ul><h3>Inverted Dependency Direction</h3><p>The Dependency Inversion Principle inverts this traditional dependency direction:</p><ol><li><strong>High-level modules should not depend on low-level modules. Both should depend on abstractions.</strong></li><li><strong>Abstractions should not depend on details. Details should depend on abstractions.</strong></li></ol><p>By applying DIP, both high-level and low-level modules depend on abstractions (interfaces or abstract classes) instead of each other directly. This creates an inverted dependency flow:</p><ul><li><strong>High-Level Module</strong> (e.g., Business Logic) → <strong>Abstraction</strong> (e.g., Service Interface) ← <strong>Low-Level Module</strong> (e.g., Database Service Implementation)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLlumZJBJnzpmnj8-CEF7g.png" /></figure><h3>Traditional Dependency vs. Inverted Dependency</h3><p>To understand DIP better, let’s consider a relatable analogy from everyday life.</p><h3>Traditional Dependency: A Restaurant and Its Suppliers</h3><p>Imagine a restaurant that prepares dishes using ingredients supplied directly by local farmers and fishers. The restaurant owner knows each supplier and orders specific ingredients from them.</p><ul><li><strong>High-Level Module</strong>: Restaurant (Business Logic)</li><li><strong>Low-Level Module</strong>: Farmers and Fishers (Details)</li></ul><p>In this setup, the restaurant is tightly coupled with the suppliers. If a supplier changes (e.g., a farmer retires), the restaurant owner needs to find a new supplier and adjust the ordering process.</p><h3>Inverted Dependency: Restaurant and a Food Distributor</h3><p>Now, imagine a different scenario where the restaurant works with a food distributor instead of individual suppliers. The restaurant orders ingredients from the distributor, who sources them from various farmers and fishers.</p><ul><li><strong>High-Level Module</strong>: Restaurant (Business Logic)</li><li><strong>Abstraction</strong>: Food Distributor (Interface)</li><li><strong>Low-Level Module</strong>: Farmers and Fishers (Details)</li></ul><p>Here, the restaurant depends on an abstraction (the distributor), and the distributor handles the details of sourcing ingredients. If a farmer retires, the distributor finds a new one without affecting the restaurant. This setup is much more flexible and easier to manage.</p><h3>Applying the Analogy to Software Design</h3><p>In software design, traditional dependency looks like this</p><pre>public class OrderProcessor {<br>    private DatabaseService databaseService;<br><br>    public OrderProcessor() {<br>        this.databaseService = new DatabaseService();<br>    }<br><br>    public void processOrder(Order order) {<br>        databaseService.saveOrder(order);<br>    }<br>}</pre><p>Here, the OrderProcessor class (restaurant) is tightly coupled with DatabaseService (suppliers). Any change in DatabaseService affects OrderProcessor.</p><p>By applying DIP, we invert the dependency:</p><pre>public interface DataService {<br>    void saveOrder(Order order);<br>}<br><br>public class DatabaseService implements DataService {<br>    @Override<br>    public void saveOrder(Order order) {<br>        // Implementation details<br>    }<br>}<br><br>public class OrderProcessor {<br>    private DataService dataService;<br><br>    public OrderProcessor(DataService dataService) {<br>        this.dataService = dataService;<br>    }<br><br>    public void processOrder(Order order) {<br>        dataService.saveOrder(order);<br>    }<br>}</pre><p>Now, OrderProcessor depends on DataService (distributor) rather than DatabaseService directly. This makes OrderProcessor more flexible and decoupled from the implementation details.</p><h3>Benefits of Dependency Inversion</h3><h3>1. Flexibility</h3><p>By depending on abstractions, we can easily switch out implementations. For example, we can replace DatabaseService with WebService without changing OrderProcessor.</p><h3>2. Testability</h3><p>Unit testing becomes simpler because we can mock the abstractions (DataService) rather than dealing with concrete implementations. This allows us to test OrderProcessor in isolation.</p><h3>3. Maintainability</h3><p>Systems built with DIP are easier to maintain and extend. Changes in low-level modules (like data storage) do not ripple through the high-level business logic.</p><h3>Practical Implementation: Using Dependency Injection</h3><p>To effectively implement DIP in your projects, you can use Dependency Injection (DI) frameworks. DI frameworks manage the creation and injection of dependencies, making your code cleaner and more maintainable.</p><h3>Example with Spring (Java)</h3><pre>@Service<br>public class OrderProcessor {<br>    private final DataService dataService;<br><br>    @Autowired<br>    public OrderProcessor(DataService dataService) {<br>        this.dataService = dataService;<br>    }<br><br>    public void processOrder(Order order) {<br>        dataService.saveOrder(order);<br>    }<br>}<br><br>@Configuration<br>public class AppConfig {<br>    @Bean<br>    public DataService dataService() {<br>        return new DatabaseService();<br>    }<br>}</pre><p>In this Spring example, OrderProcessor depends on the DataService interface, and the actual implementation (DatabaseService) is injected at runtime.</p><h3>Conclusion</h3><p>The Dependency Inversion Principle is crucial for creating flexible, maintainable, and testable software. By inverting dependencies and relying on abstractions, we decouple high-level modules from low-level implementation details. This principle, though initially counterintuitive, leads to more robust and adaptable software systems.</p><p>Next time you’re designing a system, think about the restaurant and the food distributor. Aim to create abstractions that decouple your high-level business logic from the low-level implementation details, and enjoy the benefits of a more flexible and maintainable codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa32d117ff4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detection and Mitigation of UI Rendering Performance Issues of Android Apps]]></title>
            <link>https://er-abhishek-luthra.medium.com/detection-and-mitigation-of-ui-rendering-performance-issues-of-android-apps-24d9f6d4205e?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/24d9f6d4205e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 10:10:38 GMT</pubDate>
            <atom:updated>2022-12-18T10:21:38.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>1 Introduction</h3><p>The agenda of this research is to look for Android SDK tools and developer options available to detect UI rendering nonfunctional performance issues and check the effectiveness of each considered tool and developer option in detecting the UI rendering performance issues. This study will be very helpful to detect the UI rendering performance issues efficiently in Android applications. We will approach the research by answering two different research questions :</p><p>RQ1: What are different Android SDK tools and on-device developer options for detecting different categories of UI rendering non-functional performance issues on Android?</p><p>This study has the objective of identifying the tools which can tentatively help developers in detecting any UI rendering issues in android applications. Knowing the tools available as part of the standard Android software development kit can help developers in detecting UI rendering issues in the development stage of the app itself and can also help developers in debugging the rendering issues when the app has been rolled out to production users. This can save a lot of time that developers spend doing hit and trial to see which tools may work for the type of rendering issues that they are trying to resolve.</p><p>RQ2: How effective are different Android SDK tools and on-device developer options in detecting different categories of UI rendering non-functional performance issues on Android?</p><p>Our hypothesis is that not all tools shortlisted in RQ1 will be equally effective in detecting different category of UI rendering performance issues. While a certain tool may be quite effective in certain categories of UI rendering performance issues, it may not be of much use for certain other categories of rendering issues.</p><p>It is very important to have the classification of different rendering issues done into different categories before we start addressing RQ2. We did an extensive literature review to find out a taxonomy of performance bugs in android applications. We will utilize the taxonomy as described in Figure 25 in a study done by <a href="https://doi.org/10.1007/s10664-019-09795-6">Alejandro, Catia, and Gabriele[14]</a> where they investigated types of performance bugs in android applications. The categorization of the performance issues described in the study is very thorough and will be good to test our shortlisted tools against these categories.</p><h3>2 Methodology</h3><h3>2.1 RQ1 — Qualitative approach</h3><p>A qualitative research methodology was chosen for RQ1. As part of the qualitative approach, we go through the Android developer documentation website [13] and went through most of the documentation to find out the tooling available as of Android 12 API level and Android Studio Chipmunk. As part of reading the documentation, we went on to list the performance tools found from the documentation along with the weblinks where the documentation for the same was found. Any tool which had reference to the word ‘performance’ was taken as a raw sample set of available tools in Android documentation. Out of the raw set of performance tools, we filtered out the ones which also had reference to any of the following list of words :</p><p><em>UI rendering, slow rendering, jank, skip frames, GPU, inflation, swap buffers, draw, measure, layout, canvas, bitmap, or any reference to any UI component like a listview, recycler view, and animation</em></p><p>The reason for choosing the above list of words was that all of these words are related to the user interface.</p><p>We went ahead to go through the documentation of the resultant list more thoroughly to understand which of these tools are Device( Android) tools and which ones are available as part of Android Studio, which is the standard IDE for Android development, built on top of Jetbrains Intellij IDE(Integrated Development Environment). The below List summarises the final set of tools that were considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMdOSQGdIwp6ZjuKL3C5QQ.png" /></figure><h4>2.1.1 Layout Inspector</h4><p>Layout Inspector is a tool available for developers in Android Studio IDE that lets developers see a magnified and 3D view of the entire view hierarchy. This is very useful when the layout hierarchy needs to be inspected to check for nested layouts and 3D view lets users see a 3d view of the overlapping layers in the layout hierarchy. The new layout inspector was launched in Android Studio 4.0.</p><p>The below Figure shows how to launch the layout inspector in Android Studio and the different components in the output result of the layout inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DlDp1vGIVg_orbJE" /></figure><p><em>Figure 26. The layout inspector</em></p><h4>2.1.2 Debug GPU overdraw</h4><p>Android devices contain on-device developer options which help developers in visualizing when and where the problem arises in the UI rendering pipeline. One such tool is Debug GPU overdraw which enables anyone to see if overdraw is occurring on the UI by color coding the UI with different colors according to the number of overdraw layers. This clearly identifies parts of the UI where the extra drawing has been done to render a UI layer that has been overlapped with another visible UI layer. The drawing effort on the overlapped layer is wasted as it is not visible to the end user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ilCHM8md0MMRq8cN" /></figure><p><em>Figure 27. App as it appears normally and as it appears with Debug GPU overdraw enabled</em></p><h4>2.1.3 Profile GPU rendering</h4><p>Profile GPU rendering is another developer option that developers can leverage to identify when and where the app might be having issues in the rendering pipeline. Every GPU has a specified fill rate (the speed at which the frame buffer can be refilled). If the number of pixels that are drawn on the screen increases, the GPU will take longer to process the pixels and the rest of the system will have to wait until the GPU can catch up. Profile GPU rendering presents a scrollings histogram of the frames rendered on the UI window relative to 16.6 ms frame timing. The moment any bar on the histogram crossed 16.6 ms frame timings, there is a clear drop in the frame rate which is visible as UI jank to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iIrwXDaASxeqmP4m" /></figure><p><em>Figure 28. Enlarged Profile GPU rendering graph</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*irPG7r5bFYYg4BZ6" /></figure><p><em>Figure 29. Profile GPU rendering bars in Android 6 and higher</em></p><h4>2.1.4 Show Surface updates</h4><p>Show surface updates is another developer option that if enabled flashes the part of the screen whenever the screen is refreshing. Whenever the UI on the screen is updated ( be it visible or not to the naked eye), Show surface updates will flash the screen to let developers know when the screen is refreshed. It is particularly useful to see if any animation is causing screen refresh but that animation may be overlapped by another view such that the animation is not visible to the end user. In such cases, the screen will keep flashing even if there is no considerable change in the UI of the screen. Such animations should be disabled once detected. Another use of show surface updates is in detecting considerable jank while using the app. If the screen does not flash when the user is expecting the UI to change, it clearly identifies a bad app behavior that does not update the UI when the UI should be updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*Ec2VS5UlKgrLzjCb" /></figure><p><em>Figure 30. Show surface updates developer option</em></p><h4>2.1.5 Android CPU profiler</h4><p>Android CPU profiler is a developer tool available as part of Android studio which can help in recording the app’s CPU usage and thread activity. CPU profiler records detailed information related to CPU activity. There are two types of CPU activity recordings available as part of the CPU profiler :</p><p>1. <strong>System Trace</strong>: This records very fine details about the app&#39;s interaction with the android system resources</p><p>2. <strong>Method and function trace</strong> This records which methods (java) and functions (c++/c) are running over a period of time for each thread involved in the app process. Additionally, it records the CPU resources consumed by each method or function during the execution. It also enables to the record of the callers and callees of the function. This helps in detecting who calls resource-heavy tasks and app code can be optimized to avoid such unnecessary operations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MTtmHQMeYR54hGSl" /></figure><p><em>Figure 31. The CPU profiler overview</em></p><h3>2.2 RQ2 — Quantitative approach</h3><p>For RQ2, we will use a quantitative approach to analyze the effectiveness of each of the developer tools against each of the different types of UI rendering performance issues.</p><p>Here different types refer to different categories of GUI-related issues in figure 26. These categories are mentioned below in section 3.2.1.1</p><h4>2.2.1 Performance Issue categorization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ispX_Vkpb75J39H-" /></figure><p><em>Figure 32. Taxonomy of UI rendering performance issues found in android apps</em></p><h4>2.2.2 Data Collection</h4><p>For each issue category, we will create a sample android application to demonstrate the UI rendering performance issue. For each of the seven categories, we will create seven different applications. In order to keep all the performance issues demonstrable using a single codebase, we create one android project and host that on the github[15]. For each of the issue categories, we create one git branch and host the code on that branch. The different branches are mentioned below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aQz40yTJED5C-Tot" /></figure><p><em>Figure 33. Different git branches to demonstrate each of the performance issues in android apps</em></p><p>We further create new releases for the project from each of the branches to keep a permanent reference for everyone to be able to reproduce the issue. Here are the different releases created :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IMXsIVTH1XtOszOD" /></figure><p><em>Figure 34. Different releases were created for each of the performance issues</em></p><p>Then we will apply each of our test tools to the sample android application created to demonstrate a particular category of performance issue. This means that all five tools will be applied to each category. As the research focuses on effectiveness in detecting the issues using each of these tools and the solution is already known and available, we also test the same tools on the fixed code too. This way, we check the difference in the output generated by applying each of the tools on both the performance degraded and fixed code to check how effective a particular tool is in testing that issue category. The figure below illustrates the issues taken for each of the issue categories for running our research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7PNeMpit71zqnXaG" /></figure><p><em>Figure 35. Issues taken for research for each of the UI rendering issue categories found in android apps</em></p><h4>2.2.3 Interpretation and analysis</h4><p>Each of the performance tools produces a different kind of output. So, the analysis done by each of the tools is going to be different. For each of the tools, we have to mention a metric that we are going to monitor for each of the issues we will test on. The below table mentions the primary metric we will observe for each of the tools tested :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-B4D2jzlN2dPwyloAe31yQ.png" /></figure><h3>4. Implementation And Testing</h3><p>There are seven issue categories that will be tested against 5 different developer tools to test the effectiveness of each of the tools in detecting. For each issue category, two sample projects are created. One sample project comes with the UI rendering performance issue which is going to be tested while the other sample project will have the fix done to remove that UI rendering performance issue. Each developer tool will be tested against both samples. This leads to 5 *7*2 = 70 tool tests which will be conducted to check the effectiveness of each of the considered developer tools in detecting different categories of UI rendering issues.</p><ol><li><a href="https://er-abhishek-luthra.medium.com/1-testing-the-effectiveness-of-different-android-tools-in-testing-nestedviewhierarchy-issues-on-45493f49c33c"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by NestedViewHierarchy issues on Android</em></a></li></ol><p>2. <a href="https://er-abhishek-luthra.medium.com/4-2-fibonacci-computation-on-main-thread-a4d4a6adbfc7"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by Android Fibonacci Computation on Main Thread</em></a></p><p>3. <a href="https://er-abhishek-luthra.medium.com/3-testing-the-effectiveness-of-different-android-tools-in-expensive-on-bind-call-in-recyclerview-25210e37f8b8"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by Expensive on Bind Call in RecyclerView</em></a></p><p>4. <a href="https://er-abhishek-luthra.medium.com/4-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-81738dd99ec8"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by Overdraw in Custom Views</em></a></p><p>5. <a href="https://er-abhishek-luthra.medium.com/5-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-929b12603315"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by Oversize Image Rendering</em></a></p><p>6. <a href="https://er-abhishek-luthra.medium.com/4-6-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-92f16572f4de"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by Animation without Hardware Layers</em></a></p><p>7. <a href="https://er-abhishek-luthra.medium.com/7-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-e1a54f1c87da"><em>Testing the effectiveness of different Android Tools in detecting performance issues caused by data fetch from Room Db without indexing</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24d9f6d4205e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7. Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/7-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-e1a54f1c87da?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a54f1c87da</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 09:13:29 GMT</pubDate>
            <atom:updated>2022-12-18T09:13:29.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>7. Testing the effectiveness of different Android Tools in detecting performance issues caused by data fetch from Room Db without indexing</h3><h3>7.1 Introduction</h3><p>Apps which has a lot of structured data handling use persistent on-device DB storage a lot. Database queries are one of the most commonly used data-loading operations used in Android.</p><p>Android uses SQLite database which is an open-source SQL on-device database. As a result, running inefficient queries to achieve the same task can have a lot of impact on UI rendering performance if SQLite queries are running on the main thread. As part of this test, we will test the inefficiency of fetching calls on a particular non-indexed column in an SQLite table.</p><h3>7.2 Code Implementation of Test</h3><p>As part of testing the effectiveness of different tools in UI rendering performance degradation due to data loading in Android, we created a test application where we fetch data from a non-indexed column of a table in the Room Sqlite database[21]. This table consists of 10000 rows of person entity. 1000 fetch queries are made on a nonindexed column of the table with a name stored at the 9800th row. This operation is quite expensive and blocks the main thread for a considerable period of time. To verify that the tool test results are correct in pinpointing the real cause of UI jank in this case( which is an expensive data loading call on the main thread), we ran the same tools with the same application but with indexing done on fetch column in Room Database[22].</p><p>The DataOperationsActivity ( Code 33 ) consists of a gif of an animated dancing cartoon. At the launch of the activity, the animation is clearly visible smoothly. When a user clicks on ‘Fetch Person By Name’ on the screen, 1000 SQL fetch call is made on the Person table on the firstName column. In one case data fetch happens with no index on firstName column and in another case data fetch happens using the index on firstName column. When data fetch without an index is happening, the main thread is completely occupied with data fetch calls and the animation is stalled momentarily as the animation also runs on the main thread. When data fetch with index is happening, the data fetch completes very quickly and the animation is not stalled and there is no UI jank. In the next sections, we will apply different tools to check their effectiveness in detecting UI jank caused by data loading from DB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*35r07AhArW4E-8df" /></figure><p><em>Figure 135. Image demonstrating DataOperationsActivity UI</em></p><h4>7.2.1 DataOperationsActivity.java</h4><pre>package com.example.perforamancetest;<br>import static com.example.perforamancetest.TestApplication.FIRST_NAME;<br>import static com.example.perforamancetest.TestApplication.LAST_NAME;<br>import android.app.Activity;<br>import android.os.Bundle;<br>import android.webkit.WebView;<br>import android.widget.TextView;<br>import com.example.perforamancetest.data.Person;<br>import com.example.perforamancetest.data.PersonDao;<br>import com.example.perforamancetest.data.PersonDataBase;<br>import com.example.performancetest.R;<br><br>/**<br>* Demonstration Activity to present aview showing overlapping stack of cards. This will demonstrate difference in UI rendering performance<br>* for both View with extra drawing and another with clipping to avoid drawing areas of the screen which are not visible<br>*/<br>public class DataOperationsActivity extends Activity {<br> @Override<br> public void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.activity_db_operations);<br> WebView webView = (WebView) findViewById(R.id.webview);<br> webView.getSettings().setUseWideViewPort(true);<br> webView.getSettings().setLoadWithOverviewMode(true);<br> webView.loadUrl(&quot;file:///android_asset/dancing_cartoon.gif&quot;);<br> PersonDataBase personDataBase =((TestApplication)getApplication()).getPersonDataBase();<br> PersonDao personDao = personDataBase.personDao();<br> TextView textView = findViewById(R.id.tv_name);<br> findViewById(R.id.btn_get_data).setOnClickListener(v -&gt; {<br> textView.setText(&quot;In Progress&quot;);<br> for( int index =0; index&lt;1000; index++){<br> Person person = personDao.findByFirstName(FIRST_NAME);<br> textView.setText(person.firstName + &quot; &quot; + person.lastName);<br> }<br> textView.setText(&quot;Done&quot;);<br> });<br> }<br>}</pre><p><em>Code 33. DataOperationsActivity.java</em></p><h4>7.2.2 activity_db_operations.xml</h4><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:id=&quot;@+id/activity_droid_cards_container&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br> android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br> tools:context=&quot;com.example.perforamancetest.DataOperationsActivity&quot;<br> tools:ignore=&quot;MissingDefaultResource&quot;&gt;<br> &lt;Button<br> android:id=&quot;@+id/btn_get_data&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_marginTop=&quot;32dp&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintTop_toTopOf=&quot;parent&quot;<br> android:text=&quot;Fetch Data using FirstName&quot;/&gt;<br><br> &lt;TextView<br> android:id=&quot;@+id/tv_name&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_marginTop=&quot;32dp&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintTop_toBottomOf=&quot;@id/btn_get_data&quot;<br> android:hint=&quot;data will be displayed here &quot;<br> /&gt;<br> &lt;WebView<br> android:layout_width=&quot;300dp&quot;<br> android:layout_height=&quot;300dp&quot;<br> android:id=&quot;@+id/webview&quot;<br> android:layout_gravity=&quot;center_horizontal&quot;<br> app:layout_constraintTop_toBottomOf=&quot;@id/tv_name&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> android:layout_marginTop=&quot;32dp&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p><em>Code 34. activity_db_operations.xml</em></p><h4>7.2.3 Person.java</h4><pre>package com.example.perforamancetest.data;<br>import androidx.room.ColumnInfo;<br>import androidx.room.Entity;<br>import androidx.room.Index;<br>import androidx.room.PrimaryKey;<br>@Entity<br> (indices = {@Index(&quot;first_name&quot;)})<br>public class Person {<br> @PrimaryKey<br> public int uid;<br> @ColumnInfo(name = &quot;first_name&quot;)<br> public String firstName;<br> @ColumnInfo(name = &quot;last_name&quot;)<br> public String lastName;<br>}</pre><p><em>Code 35. Person.java</em></p><h4>7.2.4 PersonDataBase.java</h4><pre>package com.example.perforamancetest.data;<br>import androidx.room.Database;<br>import androidx.room.RoomDatabase;<br><br>@Database(entities = {Person.class}, version = 1)<br>public abstract class PersonDataBase extends RoomDatabase {<br> public abstract PersonDao personDao();<br>}</pre><p><em>Code 36. PersonDataBase.java</em></p><h4>7.2.5 PersonDao.java</h4><pre>package com.example.perforamancetest.data;<br>import androidx.room.Dao;<br>import androidx.room.Delete;<br>import androidx.room.Insert;<br>import androidx.room.OnConflictStrategy;<br>import androidx.room.Query;<br>import java.util.List;<br>@Dao<br>public interface PersonDao {<br> @Query(&quot;SELECT * FROM Person&quot;)<br> List&lt;Person&gt; getAll();<br> @Query(&quot;SELECT * FROM Person WHERE uid IN (:userIds)&quot;)<br> List&lt;Person&gt; loadAllByIds(int[] userIds);<br> @Query(&quot;SELECT * FROM Person WHERE first_name = :first LIMIT 1&quot;)<br> Person findByFirstName(String first);<br> @Query(&quot;SELECT * FROM Person WHERE uid = :id&quot;)<br> Person findById(int id);<br> @Insert(onConflict = OnConflictStrategy.REPLACE) // or OnConflictStrategy.IGNORE<br> void insert(Person user);<br> @Delete<br> void delete(Person user);<br>}</pre><p><em>Code 37. PersonDao.java</em></p><h4>7.2.5 TestApplication.java</h4><pre>package com.example.perforamancetest;<br>import androidx.room.Room;<br>import com.example.perforamancetest.data.Person;<br>import com.example.perforamancetest.data.PersonDataBase;<br>public class TestApplication extends android.app.Application {<br> PersonDataBase personDataBase ;<br> public static String FIRST_NAME = &quot;Abhishek&quot;;<br> public static String LAST_NAME = &quot;Luthra&quot;;<br> @Override<br> public void onCreate() {<br> super.onCreate();<br> personDataBase = Room.databaseBuilder(getApplicationContext(),<br> PersonDataBase.class, &quot;personDatabase&quot;).allowMainThreadQueries().build();<br> addDataToDb();<br> }<br> private void addDataToDb(){<br> for( int index =0; index&lt;10000; index++){<br> Person person = new Person();<br> person.uid = index;<br> if(index == 9800){<br> person.firstName = FIRST_NAME;<br> person.lastName = LAST_NAME;<br> }<br> else{<br> person.firstName = &quot;Ram&quot; + Math.random();<br> person.lastName =&quot;Gupta&quot; + Math.random();<br> }<br> personDataBase.personDao().insert(person);<br> }<br> }<br> public PersonDataBase getPersonDataBase(){<br> return personDataBase;<br> }<br>}</pre><h3>7.3 Tool Test</h3><h4>7.3.1 LayoutInspector Tool Test</h4><p><strong>7.3.1.1 LayoutInspector on SQL fetch on non-indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lStUkKr4xxao4tOt" /></figure><p><em>Figure 136. LayoutInspector result on DataOperationsActivity with SQLite DB fetch calls on non-indexed columns of the table with large data</em></p><p><strong>7.3.1.2 LayoutInspector on SQL fetch on indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rAfGWkKK558tGK3v" /></figure><p><em>Figure 137. LayoutInspector result on DataOperationsActivity with SQLite DB fetch calls on indexed columns of the table with large data</em></p><p><strong>7.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from the component tree of Figure 136 and Figure 137 that the layout hierarchy for both is the same. This indicates LayoutInspector is ineffective in detecting any UI performance degradation due to SQLite fetch call on a non-indexed column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPBZl-kI5DdJvDGp1xBD_g.png" /></figure><h4>7.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>7.3.2.1 Debug GPU Overdraw on SQL fetch on non-indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*2E5sAyOGXKU67lUb" /></figure><p><em>Figure 138. Debug GPU overdraw result on DataOperationsActivity with SQLite DB fetch calls on non-indexed columns of the table with large data</em></p><p><strong>7.3.2.2 Debug GPU Overdraw on SQL fetch on indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*tQRl2EMh48KXes43" /></figure><p><em>Figure 139. Debug GPU overdraw result on DataOperationsActivity with SQLite DB fetch calls on indexed columns of the table with large data</em></p><p><strong>7.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of DataOperationsActivity with SQLite DB fetch calls with and without indexing on searched columns, that there is no difference in results of applying Debug GPU on both Ui. This proves that Debug GPU overdraw tool is ineffective in detecting performance degradation due to SQLite DB fetch calls on non-indexed columns of tables with large data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSTtPDCdTrH-87fxsk7uMg.png" /></figure><h4>7.3.3 Profile GPU rendering Tool Test</h4><p><strong>7.3.3.1 Profile GPU rendering on SQL fetch on non-indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*EZucGmdRBjz_biUP" /></figure><p><em>Figure 140. Profile GPU rendering result for DataOperaionsActivity with SQLite DB fetch calls on non-indexed columns of the table with large data</em></p><p><strong>7.3.3.2 Profile GPU rendering on SQL fetch on indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*MMaj921JordTT5Ab" /></figure><p><em>Figure 141. Profile GPU rendering result with SQLite DB fetch calls on indexed columns of the table with large data</em></p><p><strong>7.3.2.3 Profil GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars for SQLite DB fetch call on non-indexed columns of a table with large data( Figure 140) and for SQLite db fetch call on indexed columns of the table with large data(Figure 141) that the rendering bars fetch calls on indexed columns are smaller in height than rendering bars for fetch calls on non-indexed columns. The increase in height of rendering bars is primarily because of the green line which represents the time that the app spends executing operations in between two frames. This operation is DB fetch call on non-indexed column of the table with quite a lot of data.</p><p>The above indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by SQLite DB fetch calls on non-indexed columns of tables with large data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1CVmqxu6V5Iq-cf1QnGZQ.png" /></figure><h4>7.3.4 Show View Updates Tool Test</h4><p><strong>7.3.4.1 Show View Updates for SQL fetch without indexing</strong></p><p>The result of applying the Show View Updates developer option on SQLite DB fetch call on non-indexed columns of the table with large <a href="https://doi.org/10.5281/zenodo.7024505">data[35]</a></p><p><strong>7.3.4.2 Show View Updates for SQL fetch with indexing</strong></p><p>The result of applying the Show View Updates developer option on SQLite DB fetch call on indexed columns of table with large <a href="https://doi.org/10.5281/zenodo.7024549">data[36]</a></p><p><strong>7.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result on non indexed columns of table with large data[35] and on indexed columns of table with large data[36] that there is a noticeable difference to the human eye in the results of applying this tool. This indicates that the Show view updates tool is effective in detecting the rendering performance issues caused by animation without hardware layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGdCcGYU17SxxANRL-_-xA.png" /></figure><h4>7.3.5 Android CPU Profiler Tool Test</h4><p>As part of this test, we will click on ‘Fetch data using First Name’ button to start fetch data from the SQLite DB. The state at the end of the test looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*p8GPvB38Esfph1L4" /></figure><p><em>Figure 142. The end state of clicking on ‘FETCH DATA USING FIRST NAME’ button.</em></p><p><strong>7.3.5.1 Android CPU Profiler tool test for SQL fetch on non-indexed columns</strong><br><strong>7.3.5.1.1 System Trace CPU Profiler output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pjS0Dfte7QareC0w" /></figure><p><em>Figure 143. The CPU profiler system trace with SQLite DB fetch calls on non-indexed columns of table with large data</em></p><p>Figure 143 presents that most of the frames are janky for SQLite DB fetch calls on non-indexed columns of tables with large data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y1y4ekjZDo6OAk0G" /></figure><p><em>Figure 144. The CPU profiler system trace — All Frame visualization with SQLite DB fetch calls on non-indexed columns of the table with large data</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_o2u5BEtkRiCKBRS" /></figure><p><em>Figure 145. The CPU profiler system trace-jank visualization with SQLite DB fetch calls on non-indexed columns of table with large data</em></p><p><strong>7.3.5.2 Android CPU Profiler tool test for SQL fetch on indexed columns</strong><br><strong>7.3.5.2.1 System Trace for SQL fetch on indexed columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZ1HkhFeHhRHHM_h" /></figure><p><em>Figure 146. The CPU profiler system trace visualization with SQLite DB fetch calls on indexed columns of table with large data</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PSZBb2GRn7IHtHv8" /></figure><p><em>Figure 147. The CPU profiler system trace — All Frame visualization with SQLite DB fetch calls on indexed columns of the table with large data</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9BFaSdb8CkUWWdc0" /></figure><p><em>Figure 148. The CPU profiler system trace — Janky Frame visualization with SQLite DB fetch calls on indexed columns of the table with large data</em></p><p>From Figure 148, we see that there is no UI jank when sql fetch call is made on indexed columns.</p><p><strong>7.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for animation for SQLite DB fetch call on non-indexed columns of the table with large data( Figure 145) and for SQLite DB fetch call on indexed columns of the table with large data(Figure 148) that the that there is the significant reduction in the number of janks frames itself by running SQLite DB fetch call on indexed columns of the table rather than non-indexed columns. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by SQLite DB fetch call on indexed columns of table with large data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vU0KY8f9HhuOQ0KQoqUJpA.png" /></figure><p>This clearly shows that there is a 100 percent improvement in the number of jank frames by indexing columns if there are frequent reads from that table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5mXJVeLMdj-gIxsbZxh6w.png" /></figure><h4>7.3.6 Tool Test Results on oversize image rendering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z-2q4tPYGvJK-5GFFofpw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a54f1c87da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6. Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/4-6-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-92f16572f4de?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f16572f4de</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 08:34:56 GMT</pubDate>
            <atom:updated>2022-12-18T08:47:07.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>6. Testing the effectiveness of different Android Tools in detecting performance issues caused by Animation without Hardware Layers</h3><h3>6.1 Introduction</h3><p>When animations are run on a device, frames are drawn in every frame. Starting with API level 11, hardware acceleration is supported by the Android 2D rendering pipeline. When hardware acceleration is enabled, drawing operations which are usually performed using View’s canvas, use the GPU for drawing. When hardware layers are used, layers get drawn once in an off-screen buffer and are later reused when the same views need to be redrawn. It saves on extra drawing operations on the main thread</p><h3>6.2 Code Implementation of Test</h3><p>In order to test the performance degradation in running animations without hardware layers, we created a UI that runs animations by moving one layout out and another layout in. We will run our tools with both hardware acceleration on and off. Ui is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*PfQjdApSHIv0DAm6" /></figure><p><em>Figure 116. Screenshot for first layout</em></p><h4>6.2.1 MainActivity.java</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>import android.animation.Animator;<br>import android.animation.AnimatorListenerAdapter;<br>import android.app.Activity;<br>import android.os.Bundle;<br>import android.view.View;<br>import android.widget.CheckBox;<br>import android.widget.TextView;<br>import androidx.annotation.DrawableRes;<br>import androidx.annotation.IdRes;<br>import androidx.annotation.StringRes;<br>import com.example.performancetest.R;<br><br>public class MainActivity extends Activity {<br><br> private View mLayout1;<br> private View mLoremIpsum1;<br> private View mLayout2;<br> private View mLoremIpsum2;<br> // When checked, this enables using hardware layers on the main layouts<br> private CheckBox mHwLayerCheckbox;<br><br> @Override<br> protected void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.activity_main);<br> mHwLayerCheckbox = (CheckBox) findViewById(R.id.hw_layers_checkbox);<br> mLayout1 = configureLayout(R.id.layout_1, R.drawable.bg_layout_1, R.string.layout1_title);<br> mLoremIpsum1 = mLayout1.findViewById(R.id.lorem_ipsum);<br> mLayout2 = configureLayout(R.id.layout_2, R.drawable.bg_layout_2, R.string.layout2_title);<br> mLoremIpsum2 = mLayout2.findViewById(R.id.lorem_ipsum);<br> // Start with one of the two hidden<br> mLayout2.setAlpha(0);<br> findViewById(R.id.animate_button).setOnClickListener(new View.OnClickListener() {<br> @Override public void onClick(View v) {<br> animate();<br> }<br> });<br> }<br> private View configureLayout(@IdRes int id, @DrawableRes int background, @StringRes int title) {<br> View layout = findViewById(id);<br> layout.setBackgroundResource(background);<br> TextView titleView = (TextView) layout.findViewById(R.id.title);<br> titleView.setText(title);<br> return layout;<br> }<br> private void animate() {<br> float layout1Alpha = mLayout1.getAlpha();<br> if (layout1Alpha != 0 &amp;&amp; layout1Alpha != 1) {<br> // Mid-animation; don&#39;t animate<br> return;<br> }<br> final View layoutIn = layout1Alpha == 0 ? mLayout1 : mLayout2;<br> final View layoutOut = layoutIn == mLayout1 ? mLayout2 : mLayout1;<br> int widthPixels = getResources().getDisplayMetrics().widthPixels;<br> float scale = .5f;<br> layoutIn.setTranslationX(widthPixels / 2);<br> layoutIn.setScaleX(scale);<br> layoutIn.setScaleY(scale);<br> layoutIn.animate()<br> .alpha(1)<br> .translationX(0)<br> .scaleX(1)<br> .scaleY(1)<br> .setListener(new AnimatorListenerAdapter() {<br> @Override<br> public void onAnimationStart(Animator animation) {<br> if (mHwLayerCheckbox.isChecked()) {<br> layoutIn.setLayerType(View.LAYER_TYPE_HARDWARE, null);<br> }<br> }<br> @Override<br> public void onAnimationEnd(Animator animation) {<br> if (mHwLayerCheckbox.isChecked()) {<br> layoutIn.setLayerType(View.LAYER_TYPE_NONE, null);<br> }<br> }<br> })<br> .start();<br> layoutOut.animate()<br> .alpha(0)<br> .translationX(-widthPixels / 2)<br> .scaleX(scale)<br> .scaleY(scale)<br> .setListener(new AnimatorListenerAdapter() {<br> @Override<br> public void onAnimationStart(Animator animation) {<br> if (mHwLayerCheckbox.isChecked()) {<br> layoutOut.setLayerType(View.LAYER_TYPE_HARDWARE, null);<br> }<br> }<br> @Override<br> public void onAnimationEnd(Animator animation) {<br> if (mHwLayerCheckbox.isChecked()) {<br> layoutOut.setLayerType(View.LAYER_TYPE_NONE, null);<br> }<br> }<br> })<br> .start();<br> final View ipsumIn = layoutIn == mLayout1 ? mLoremIpsum1 : mLoremIpsum2;<br> final View ipsumOut = layoutOut == mLayout2 ? mLoremIpsum2 : mLoremIpsum1;<br> int heightPixels = getResources().getDisplayMetrics().heightPixels;<br> int target = heightPixels / 2;<br> ipsumIn.setTranslationY(target);<br> ipsumIn.setAlpha(0);<br> ipsumIn.animate()<br> .translationY(0)<br> .alpha(1)<br> .start();<br> ipsumOut.animate()<br> .translationY(target)<br> .alpha(0)<br> .start();<br> }<br>}</pre><p><em>Code 28. MainActivity.java</em></p><h4>6.2.2 activity_main.xml</h4><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:id=&quot;@+id/activity_droid_cards_container&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br> android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br> tools:context=&quot;com.example.perforamancetest.overdraw_custom_view.ImageActivity&quot;&gt;<br> &lt;Button<br> android:id=&quot;@+id/btn_add_cards_View&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_marginTop=&quot;32dp&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintTop_toTopOf=&quot;parent&quot;<br> android:text=&quot;Show Cards View&quot;/&gt;<br> &lt;ImageView<br> android:id=&quot;@+id/image_view&quot;<br> android:layout_width=&quot;900px&quot;<br> android:layout_height=&quot;600px&quot;<br> app:layout_constraintTop_toBottomOf=&quot;@id/btn_add_cards_View&quot;<br> app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> /&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_marginBottom=&quot;8dp&quot;<br> android:orientation=&quot;horizontal&quot;<br> android:paddingLeft=&quot;8dp&quot;<br> android:paddingRight=&quot;8dp&quot;&gt;<br> &lt;LinearLayout<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_centerVertical=&quot;true&quot;<br> android:orientation=&quot;vertical&quot;&gt;<br> &lt;CheckBox<br> android:id=&quot;@+id/hw_layers_checkbox&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:text=&quot;@string/use_hw_layers&quot; /&gt;<br> &lt;/LinearLayout&gt;<br><br> &lt;Button<br> android:id=&quot;@+id/animate_button&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_alignParentRight=&quot;true&quot;<br> android:layout_centerVertical=&quot;true&quot;<br> android:text=&quot;@string/animate&quot; /&gt;<br> &lt;/RelativeLayout&gt;</pre><p><em>Code 29. activity_main.xml</em></p><h4>6.2.3 include_layout.xml</h4><pre>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:orientation=&quot;vertical&quot;<br> android:padding=&quot;8dp&quot;<br> tools:background=&quot;@drawable/bg_layout_1&quot;&gt;<br> &lt;TextView<br> android:id=&quot;@+id/title&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_gravity=&quot;center_horizontal&quot;<br> android:textSize=&quot;24sp&quot;<br> android:textStyle=&quot;bold&quot;<br> tools:text=&quot;@string/layout1_title&quot; /&gt;<br> &lt;TextView<br> android:id=&quot;@+id/lorem_ipsum&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;0dp&quot;<br> android:layout_marginTop=&quot;8dp&quot;<br> android:layout_weight=&quot;1&quot;<br> android:text=&quot;@string/lorem_ipsum&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><p><em>Code 30. include_layout.xml</em></p><h4>6.2.3 bg_layout_1.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> android:shape=&quot;rectangle&quot;&gt;<br> &lt;corners android:radius=&quot;8dp&quot; /&gt;<br> &lt;solid android:color=&quot;#88FF88&quot; /&gt;<br>&lt;/shape&gt;</pre><p><em>Code 31. bg_layout_1.xml</em></p><h4>6.2.4 bg_layout_2.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> android:shape=&quot;rectangle&quot;&gt;<br> &lt;corners android:radius=&quot;8dp&quot; /&gt;<br> &lt;solid android:color=&quot;#88FF88&quot; /&gt;<br>&lt;/shape&gt;</pre><p><em>Code 32. bg_layout_2.xml</em></p><h3>6.3 Tool Test</h3><h4>6.3.1 LayoutInspector Tool Test</h4><p><strong>6.3.1.1 LayoutInspector on the first layout without hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IGTxx-Ww09IuBKhx" /></figure><p><em>Figure 117. LayoutInspector result on the first layout without hardware layers</em></p><p><strong>6.3.1.2 LayoutInspector on the first layout with hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xqF_0oeXA0zAGWnG" /></figure><p><em>Figure 118. LayoutInspector result on the first layout with hardware layers</em></p><p><strong>6.3.1.3 LayoutInspector for the second layout without hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2zj8L0JX75yD8Q6g" /></figure><p><em>Figure 119. LayoutInspector result for the second layout without hardware layers</em></p><p><strong>6.3.1.4 LayoutInspector for the second layout with hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S9E8JPo59-dWlUqb" /></figure><p><em>Figure 120. LayoutInspector result for the second layout with hardware layers</em></p><p><strong>6.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from the component tree of Figure 117 and Figure 118 that the layout hierarchy for layout 1 remains the same with and without hardware layers. Similarly, Figure 119 and Figure 120 show that the layout hierarchy for layout 2 remains the same. This indicates LayoutInspector is ineffective in detecting any UI performance degradation due to rendering animations without hardware layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NKYCOOxvR6jDrXyXNrIew.png" /></figure><h4>6.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>6.3.2.1 Debug GPU Overdraw on the first layout in animation without hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*93XEceVmhMQ-D8vv" /></figure><p><em>Figure 121. Debug Gpu overdraw result for the first layout without hardware layers</em></p><p><strong>6.3.2.2 Debug GPU Overdraw on the second layout in animation without hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*7EJnzt2XZXjKY3Hn" /></figure><p><em>Figure 122. Debug Gpu overdraw result for the second layout without hardware layers</em></p><p><strong>6.3.2.3 Debug GPU Overdraw on the second layout in animation with hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*Q278lNEvlrdACwm3" /></figure><p><em>Figure 123. Debug Gpu overdraw result for the second layout with hardware layers</em></p><p><strong>6.3.2.4 Debug GPU Overdraw on second layout in animation with hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*YXoNu9diBLmX9wLg" /></figure><p><em>Figure 124. Debug Gpu overdraw result for the second layout with hardware layers</em></p><p><strong>6.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of both layouts without and with hardware rendering there is no difference in results of applying Debug GPU on both Ui . This proves that Debug GPU overdraw tool is ineffective in detecting performance degradation due to animations without hardware layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLo70QcvfkdGlCzQEbeojw.png" /></figure><h4>6.3.3 Profile GPU rendering Tool Test</h4><p><strong>6.3.3.1 Profile GPU rendering on animation without hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*HifKzmORPfWXqNwM" /></figure><p><em>Figure 125. Profile GPU rendering result for animation without Hardware layers</em></p><p><strong>6.3.3.2 Profile GPU rendering on animation with hardware layers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*iyI48KSKb-NKz1KB" /></figure><p><em>Figure 126. Profile GPU rendering result for animation with Hardware layers</em></p><p><strong>6.3.2.3 Profil GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars of animation without hardware layers ( Figure 125) and with hardware layers(Figure 126) that the rendering bars for animation with hardware layers are smaller in height than rendering bars without hardware layers. Moreover, the rendering bars for animation with hardware layers are below the green marker line which denotes 16.6 ms frame time. The increase in height of rendering bars without hardware layers is primarily because of the red and yellow lines. The red bars correspond to the command issue which represents the time spent by Android’s 2D renderer issuing commands to OpenGL to draw and redraw display lists. The height of this bar is directly proportional to the sum of the time it takes each display list to execute — more display lists equals a taller red bar. The yellow bar corresponds to Swap Buffers which represents the time the CPU is waiting for the GPU to finish its work.</p><p>The above indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by animation without hardware layers.</p><h4>6.3.4 Show View Updates Tool Test</h4><p><strong>6.3.4.1 Show View Updates for Animation without Hardware Layers</strong></p><p>The result of applying Show View Updates developer option on animation <a href="https://doi.org/10.5281/zenodo.7018855">without hardware layers [31]</a></p><p><strong>6.3.4.2 Show View Updates for Animation with Hardware Layers</strong></p><p>The result of applying Show View Updates developer option on animation <a href="https://doi.org/10.5281/zenodo.7018870">with hardware layers [32]</a></p><p><strong>6.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result for animation without hardware layers[31] and animation with hardware layers[32] that there is no noticeable difference to the human eye in results of applying this tool. This indicates that the Show view updates tool is ineffective in detecting the rendering performance issues caused by animation without hardware layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBA-oWXrxSUcMli8TOwvJg.png" /></figure><h4>6.3.5 Android CPU Profiler Tool Test</h4><p>As part of this test, we will click on ‘Animate button’’to play the animation both with and without hardware layers. The same animation will play as shown in [31] and [32]</p><p><strong>6.3.5.1 Android CPU Profiler tool test for Animation without Hardware layers</strong><br><strong>6.3.5.1.1 System Trace CPU Profiler output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cd6uosMF1zx2ltRL" /></figure><p><em>Figure 128. The CPU profiler system trace visualization for animation without hardware layers</em></p><p>Figure 128 presents that most of the frames are janky for animation without hardware layers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VKmF6U2DVZgE-lAo" /></figure><p><em>Figure 129. The CPU profiler system trace — All Frame visualization for animation without hardware layers</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gMqW_rdvZu9-uEcK" /></figure><p><em>Figure 130. The CPU profiler system trace — Janky Frame visualization for animation without hardware layers</em></p><p>In Figure 130, It can be seen that all the frames for animation without hardware layers are janky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0_-7i8Tyv9dG6UAN" /></figure><p><em>Figure 131. The CPU profiler system trace — This shows that expensive draw calls for every frame for animation without hardware layers</em></p><p><strong>6.3.5.2 Android CPU Profiler tool test for animation with hardware layers</strong><br><strong>6.3.5.2.1 System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*22sLgKODsVemrvTs" /></figure><p><em>Figure 132. The CPU profiler system trace visualization for animation with hardware layers</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8eT5WpdcUC-ZbK90" /></figure><p><em>Figure 133. The CPU profiler system trace — All Frame visualization for animation with hardware layers</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kj7oo3x-xPvnEVgs" /></figure><p><em>Figure 134. The CPU profiler system trace — Janky Frame visualization for animation with hardware layers</em></p><p>From Figure 134, we see that there is no UI jank when animation is run with hardware layers.</p><p><strong>6.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for animation without hardware layers and with hardware layers that there is significant reduction in number of jank frames itself by using hardware layers for animation to avoid drawing same view in each frame. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by animation without hardware layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVpUUFgGwPkdMtlPs_9UXQ.png" /></figure><p>This clearly shows that there is 100 percent improvement in number of jank frames by avoiding the rendering of oversize image in imageview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yW_V34ESkGqdfQKnO9-Tpg.png" /></figure><h4>6.3.6 Tool Test Results on oversize image rendering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UteN_5wW9XC9AfJSyqhV1g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f16572f4de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/5-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-929b12603315?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/929b12603315</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 07:57:32 GMT</pubDate>
            <atom:updated>2022-12-18T07:57:32.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>5. Testing the effectiveness of different Android Tools in detecting performance issues caused by Oversize Image Rendering</h3><h3>5.1 Introduction</h3><p>Android devices have different shapes and sizes. Each of the devices has different pixel densities.</p><p>pixel densities here refer to the number of dots per square inch of the screen. This defines the sharpness of graphics that are seen on the screen.</p><p>ImageView is the primary android component used to render images in Android Applications. Every image resource that is added to app resources has its own width and height defined in pixels. And Imageview used on the UI can also have its own width and height. It is very important to have the Image resources of the scale of the image view in which it is shown. This is important because a process called decoding is run to convert image resources to bitmap shown in the image view. The time taken for bitmap decoding is proportional to the size of the image which is being used. If the size of the image is much bigger than the size of the image view in which it is going to be shown, the system will spend extra processing time to show the same UI on the screen as the image with the same height and width of image view.</p><h3>5.2 Code Implementation of Test</h3><p>In order to test the performance degradation in rendering images of larger sizes than the image view size in comparison to rendering images of same size as image view, we will use a Samsung S21 device with xxhdpi screen density. We will add an image view of the size of 900 x 600 pixels in the activity UI. Additionally, we have two image resources with same visualization but with two heights 900 x 600 pixels and 2700 x 1800 pixels. Both of these images are in the drawable -xxhdpi folder as the screen density of the device is xxhdpi. We will then verify our hypothesis of performance degradation due to image decoding of a bigger image , by running the tools against an activity with the bigger image in the same image view.</p><h4>5.2.1 ImageActivity.java</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>import android.app.Activity;<br>import android.graphics.Bitmap;<br>import android.graphics.BitmapFactory;<br>import android.os.Bundle;<br>import android.widget.ImageView;<br>import com.example.performancetest.R;<br><br>/**<br>* Demonstration Activity to present performance degradation with showing larger image on imageview of smaller size<br>*/<br>public class ImageActivity extends Activity {<br> private ImageView imageView;<br><br> @Override<br> public void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.activity_images);<br> imageView = findViewById(R.id.image_view);<br> findViewById(R.id.btn_add_cards_View).setOnClickListener(v -&gt; {<br> Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.image_resource_2700_1800);<br> imageView.setImageBitmap(bitmap);<br> });<br> }<br>}</pre><p><em>Code 26. ImageActivity.java</em></p><h4>5.2.2 activity_images.xml</h4><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:id=&quot;@+id/activity_droid_cards_container&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br> android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br> tools:context=&quot;com.example.perforamancetest.overdraw_custom_view.ImageActivity&quot;&gt;<br> &lt;Button<br> android:id=&quot;@+id/btn_add_cards_View&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_marginTop=&quot;32dp&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintTop_toTopOf=&quot;parent&quot;<br> android:text=&quot;Show Cards View&quot;/&gt;<br> &lt;ImageView<br> android:id=&quot;@+id/image_view&quot;<br> android:layout_width=&quot;900px&quot;<br> android:layout_height=&quot;600px&quot;<br> app:layout_constraintTop_toBottomOf=&quot;@id/btn_add_cards_View&quot;<br> app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> /&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p><em>Code 27. activity_images.xml</em></p><h4>5.2.3 image_resource_900_600.java</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*rDsWp9eva2wsISs4" /></figure><p><em>Figure 100. Image of 900 X 600 pixel dimension</em></p><h4>5.2.4 image_resource_2700_1800.java</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UoQC_Cnyq3OH1lva" /></figure><p><em>Figure 101. Image of 2700 X 1800 pixel dimension</em></p><h3>5.3 Tool Test</h3><h4>5.3.1 LayoutInspector Tool Test</h4><p><strong>5.3.1.1 LayoutInspector on Oversize Image Rendering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EsXlc3Xhw9YnsSyP" /></figure><p><em>Figure 102. LayoutInspector result for 2700 x 1800 pixel dimension image</em></p><p><strong>5.3.1.2 LayoutInspector on Correct Size Image rendering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YGkmzlP6damav61N" /></figure><p><em>Figure 103. LayoutInspector result for 900 x 600 pixel dimension image</em></p><p><strong>5.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from the component tree of Figure 102 and Figure 103 that the layout hierarchy for both layouts with 900 X 600 and 2700 X 1800 pixel dimension images is the same. This indicates LayoutInspector is ineffective in detecting any UI performance degradation due to oversize image rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bwLk2ATNpivWH98QphSNA.png" /></figure><h4>5.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>5.3.2.1 Debug GPU Overdraw on oversize image rendering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*JVZ34PZ9ca-JER0B" /></figure><p><em>Figure 104. Debug Gpu overdraw result for oversize image rendering</em></p><p><strong>5.3.2.2 Debug GPU Overdraw on correct size image rendering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*nanJREFmDCa784eu" /></figure><p><em>Figure 105. Debug Gpu overdraw result for Correct Size image rendering</em></p><p><strong>5.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of Oversize image rendering(Figure 104) and correct size image rendering(Figure 105) that there is no difference in results of applying Debug GPU overdraw tool on both UI . This proves that Debug GPU overdraw tool is ineffective in detecting performance degradation due to oversize image rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWgWyTNWWt0KmJD60aXz9g.png" /></figure><h4>5.3.3 Profile GPU rendering Tool Test</h4><p><strong>5.3.3.1 Profile GPU rendering on oversize image rendering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*LiUZ4a0Tl6Ggyrvj" /></figure><p><em>Figure 106. Profile GPU rendering result for oversize image rendering</em></p><p><strong>5.3.3.2 Profile GPU rendering on correct size image rendering</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*RWhRdAb_oEfaEucc" /></figure><p><em>Figure 107. Profile GPU rendering result for Correct size image rendering</em></p><p><strong>5.3.2.3 Profil GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars of Oversize Image rendering ( Figure 106) and correct size image rendering(Figure 107) that the rendering bars with correct size image rendering are smaller in height than rendering bars with oversize image rendering. Moreover, the rendering bars for correct size image rendering are below the red marker line which denote 16 ms frame time. The first high bar above green marker line for both correct size image rendering and oversize image rendering are because of launcher activity launch for the app. We exclude that bar for our analysis and only consider remaining bars which are drawn after button is pressed and image is rendered. The increase in height of rendering bars for oversize is primarily because of the red and orange lines. The red bars correspond to command issue which represents the time spent by Android’s 2D renderer issuing commands to OpenGL to draw and redraw display lists. The height of this bar is directly proportional to the sum of the time it takes each display list to execute — more display lists equals a taller red bar. The yellow bar correspond to Swap Buffers which represents the time the CPU is waiting for the GPU to finish its work. If this bar gets tall, it means the app is doing too much work on the GPU.</p><p>Above indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by oversize image rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hok8X9BC8pmfHGFPuj8dCQ.png" /></figure><h4>5.3.4 Show View Updates Tool Test</h4><p><strong>5.3.4.1 Show View Updates for FibonacciActivity.java on oversize image rendering</strong></p><p>The result of applying Show View Updates developer option on oversize image <a href="https://doi.org/10.5281/zenodo.7017074">rendering [29]</a></p><p><strong>5.3.4.2 Show View Updates for FibonacciActivity.java on correct image rendering</strong></p><p>The result of applying Show View Updates developer option on correct size image <a href="https://doi.org/10.5281/zenodo.7017092">rendering [30]</a></p><p><strong>5.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result for oversize image rendering[29] and correct size image rendering[30] that there is significant difference in results of applying this tool. The view updates slow down when rendering oversize image. This indicates that the Show view updates tool is effective in detecting the rendering performance issues caused by oversize image rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfXaYOqizgqJrXVwsQHzNg.png" /></figure><h4>5.3.5 Android CPU Profiler Tool Test</h4><p><strong>5.3.5.1 Android CPU Profiler tool test for oversize image rendering</strong><br><strong>5.3.5.1.1 System Trace CPU Profiler output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gM9RenzVFuUWQVLj" /></figure><p><em>Figure 109. The CPU profiler system trace visualization for oversize image rendering in imageview</em></p><p>Figure 109 presents that most of the frames are janky after pressing button to show the oversized image on imageview</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ERoq8Gc1V6ziXfSj" /></figure><p><em>Figure 110. The CPU profiler system trace — All Frame visualization for oversize image rendering in imageview</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qqJM37b3fMNdtZ6j" /></figure><p><em>Figure 111. The CPU profiler system trace — Janky Frame visualization for oversize image rendering in imageview</em></p><p>In Figure 111, it can be observed all the frames for oversize image rendering are janky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WvCpHtya6VO1cIL8" /></figure><p><em>Figure 112. The CPU profiler system trace visualization for oversize image rendering in imageview</em></p><p>In Figure 112, It can be seen that decodeBitmap and draw calls are one major cause of the jank frames.</p><p><strong>5.3.5.2 Android CPU Profiler tool test for Correct Size Image rendering</strong><br><strong>5.3.5.2.1 System Trace CPU Profiler output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KxnunCWb-hrvLiva" /></figure><p><em>Figure 113. The CPU profiler system trace visualization for Correct Size image rendering in Imageview</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BXS1iTHu-qbAcFRo" /></figure><p><em>Figure 114. The CPU profiler system trace — All Frame visualization for Correct Size image rendering in Imageview</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-pCU_gyxqmdpbI7S" /></figure><p><em>Figure 115. The CPU profiler system trace — Janky Frame visualization for Correct Size image rendering in Imageview</em></p><p>From Figure 115, we see that there is no UI jank when OptimizedCardsView is rendered on the screen.</p><p><strong>5.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for oversize image rendering and correct size image rendering in imageview that there is significant reduction in number of jank frames by using image of the size of imageview rather than using image of size much bigger than imageview provided all other aspects of image apart from dimensions remain the same. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by oversize image rendering in imageview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdy1EoXut8bgZmwuNRLHrg.png" /></figure><p>This clearly shows that there is 100 percent improvement in number of jank frames by avoiding the rendering of oversize image in imageview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeFlY-Wxvl3_3iobcYxjzw.png" /></figure><h4>5.3.6 Tool Test Results on oversize image rendering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ygQ1vn4sTcBNdMBiiijkA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=929b12603315" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4. Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/4-testing-the-effectiveness-of-different-android-tools-in-detecting-performance-issues-caused-by-81738dd99ec8?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/81738dd99ec8</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 07:42:26 GMT</pubDate>
            <atom:updated>2022-12-18T07:42:26.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>4. Testing the effectiveness of different Android Tools in detecting performance issues caused by Overdraw in Custom Views</h3><h3>4.1 Introduction</h3><p>Many times, a view is drawn which is obscured by another view on top of it. This leads to extra overdrawing and which is wasted processing power. For the default widgets available in the android framework, the code handles avoiding overdrawing when the widget is obscured by another view. This is called clipping in Android.</p><p>When custom views are created in Android, the Android framework is not aware of how drawing is going to happen and completely relies on code inside onDraw call inside view to draw the view on the screen. If hidden parts of the custom view are also drawn, it leads to extra CPU and GPU processing power and can contribute to UI jank.</p><h3>4.2 Code Implementation of Test</h3><p>Figure 86 shows a custom view drawing of a stack of 30 cards with names and bitmap images. A major portion of all the cards is obscured apart from last card. . If Android goes on to draw all the cards completely, the system wastes a lot of CPU and GPU processing in drawing those cards. This contributes to UI jank as a lot of CPU and GPU time is spent in rendering the first two cards which is not even needed.</p><p>In order to test this pattern, we run tests using tools on two different views rendering the same visualization on the screen. One view will draw all the thirty cards completely[86] and the other view will just draw areas of the cards which are visible on the screen[87]. We will run our tools against the overdrawn view to check their effectiveness in detecting UI rendering performance degradation due to overdrawing in custom views. We will then verify our hypothesis of performance degradation due to overdrawing in custom views, by running the tools against an optimized view in which only visible portions of the cards are drawn.</p><h4>4.2.1 CardsActivity.java</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>import android.app.Activity;<br>import android.os.Bundle;<br>import android.view.View;<br>import android.widget.FrameLayout;<br>import android.widget.RelativeLayout;<br>import androidx.constraintlayout.widget.ConstraintLayout;<br>import com.example.performancetest.R;<br><br>/**<br>* Demonstration Activity to present a view showing overlapping stack of cards. This will demonstrate difference in UI rendering performance<br>* for both View with extra drawing and another with clipping to avoid drawing areas of the screen which are not visible<br>*/<br>public class CardsActivity extends Activity {<br> public static final String TAG = &quot;droid-cards-activity&quot;;<br> protected static final float DROID_IMAGE_WIDTH = 420f;<br> protected static final float CARD_SPACING = DROID_IMAGE_WIDTH / 20;<br> private FrameLayout containerView;<br><br> private ConstraintLayout mdroidCardsContainer;<br> @Override<br> public void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.activity_cards);<br> mdroidCardsContainer = findViewById(R.id.activity_droid_cards_container);<br> containerView = findViewById(R.id.container_cards_view);<br> CardModel[] cardModels = new CardModel[30];<br> for(int index =0; index❤0; index++){<br> if(index%3 ==0){<br> cardModels[index] = new CardModel(&quot;Joanna&quot;, R.color.joanna_color, R.drawable.joanna);<br> }<br> else if(index%3 ==1){<br> cardModels[index] = new CardModel(&quot;Shailen&quot;, R.color.shailen_color, R.drawable.shailen);<br> }<br> else {<br> cardModels[index] = new CardModel(&quot;Chris&quot;, R.color.chris_color, R.drawable.chris);<br> }<br> }<br> final UnOptimizedCardsView droidCardView = new UnOptimizedCardsView(<br> this,<br> cardModels,<br> DROID_IMAGE_WIDTH,<br> CARD_SPACING<br> );<br> droidCardView.setLayoutParams(new RelativeLayout.LayoutParams(<br> RelativeLayout.LayoutParams.MATCH_PARENT,<br> RelativeLayout.LayoutParams.WRAP_CONTENT));<br> findViewById(R.id.btn_add_cards_View).setOnClickListener(new View.OnClickListener() {<br> @Override<br> public void onClick(View v) {<br> containerView.addView(droidCardView);<br> }<br> });<br><br> }<br>}</pre><p><em>Code 20. CardsActivity.java</em></p><h4>4.2.2 activity_cards.xml</h4><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:id=&quot;@+id/activity_droid_cards_container&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br> android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br> tools:context=&quot;com.example.perforamancetest.overdraw_custom_view.CardsActivity&quot;&gt;<br> &lt;Button<br> android:id=&quot;@+id/btn_add_cards_View&quot;<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:layout_marginTop=&quot;32dp&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintTop_toTopOf=&quot;parent&quot;<br> android:text=&quot;Show Cards View&quot;/&gt;<br> &lt;FrameLayout<br> android:id=&quot;@+id/container_cards_view&quot;<br> android:layout_width=&quot;0dp&quot;<br> android:layout_height=&quot;0dp&quot;<br> app:layout_constraintTop_toBottomOf=&quot;@id/btn_add_cards_View&quot;<br> app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br> app:layout_constraintStart_toStartOf=&quot;parent&quot;<br> app:layout_constraintEnd_toEndOf=&quot;parent&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p><em>Code 21. activity_cards.xml</em></p><h4>4.2.3 CardModel.java</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>public class CardModel {<br> private String name;<br><br> private int color;<br><br> private int imageId;<br><br> public CardModel(String name, int color) {<br> this.name = name;<br> this.color = color;<br> }<br> public CardModel(String name, int color, int imageId) {<br> this.name = name;<br> this.color = color;<br> this.imageId = imageId;<br> }<br> public String getName() {return name;}<br> public int getColor() {return color;}<br> public int getAvatarId() {return imageId;}<br>}</pre><p><em>Code 22. CardModel.java.</em></p><h4>4.2.4 Card.java</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>import android.graphics.Bitmap;<br><br>class Card {<br> protected static final float SPACE_AROUND_IMAGE = 20f;<br> protected static final float BITMAP_HEIGHT_HEADER_HEIGHT_RATIO = .25f;<br> private CardModel mCardModel;<br> private Bitmap mBitmap;<br> private float mHeaderHeight;<br> private float mBodyHeight;<br> private float mTitleSize;<br> Card(CardModel cardModel, Bitmap bitmap) {<br> mCardModel = cardModel;<br> mBitmap = bitmap;<br> mBodyHeight = mBitmap.getHeight() + SPACE_AROUND_IMAGE;<br> mHeaderHeight = mBitmap.getHeight() * BITMAP_HEIGHT_HEADER_HEIGHT_RATIO;<br> mTitleSize = mHeaderHeight / 2;<br> }<br> private String logDimensions() {<br> return &quot;mBodyHeight = &quot; + mBodyHeight +<br> &quot;, mHeaderHeight = &quot; + mHeaderHeight +<br> &quot;, mTitleSize = &quot; + mTitleSize +<br> &quot;, getWidth() = &quot; + String.valueOf(getWidth());<br> }<br> protected float getWidth() {<br> return mBitmap.getWidth() + (2 * SPACE_AROUND_IMAGE);<br> }<br> protected float getBodyHeight() {<br> return mBodyHeight;<br> }<br> protected float getHeaderHeight() {<br> return mHeaderHeight;<br> }<br> protected float getHeight() {<br> return getBodyHeight() + getHeaderHeight();<br> }<br> protected float getTitleSize() {<br> return mTitleSize;<br> }<br> protected Bitmap getBitmap() {<br> return mBitmap;<br> }<br> protected CardModel getCard() {<br> return mCardModel;<br> }<br> protected float getTitleXOffset() {<br> return SPACE_AROUND_IMAGE;<br> }<br> protected float getTitleYOffset() {<br> return SPACE_AROUND_IMAGE;<br> }<br>}</pre><p><em>Code 23. Card.java</em></p><h4>4.2.5 UnoptimizedCardsView.java with complete drawing of overlapping cards</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>import android.content.Context;<br>import android.content.res.Resources;<br>import android.graphics.Bitmap;<br>import android.graphics.BitmapFactory;<br>import android.graphics.Canvas;<br>import android.graphics.Color;<br>import android.graphics.Paint;<br>import android.graphics.Rect;<br>import android.os.AsyncTask;<br>import android.view.View;<br>import java.lang.ref.WeakReference;<br>import java.util.ArrayList;<br>/**<br>* A custom view that presents a stacked overlapping collection of cards. OnDraw method draws the all cards<br>* completely irrespective of whether the entire card is visible or not<br>*/<br>class UnOptimizedCardsView extends View {<br> /**<br> * Array of cards to be displayed in the view.<br> */<br> private CardModel[] mCardModels;<br> /**<br> * The width of the card that needs to be shown<br> */<br> float mImageWidth;<br> /**<br> * THe difference in left edge positions of two consecutive image cards.<br> */<br> protected float mCardSpacing;<br> /**<br> * The position of the left edge of each card in the view<br> */<br> private float mCardLeft;<br> /**<br> * List of cards which needs to be shown in the view<br> */<br> private ArrayList&lt;Card&gt; mCards = new ArrayList&lt;Card&gt;();<br> /**<br> *<br> * @param context application context .<br> * @param cardModels card models for each card to be displayed.<br> * @param imageWidth The width of each card which is shown<br> * @param cardSpacing The difference in left edge positions of two consecutive image cards.<br> */<br> public UnOptimizedCardsView(Context context, CardModel[] cardModels, float imageWidth,<br> float cardSpacing) {<br> super(context);<br> mCardModels = cardModels;<br> mImageWidth = imageWidth;<br> mCardSpacing = cardSpacing;<br> // Fire AsyncTasks to fetch and scale the bitmaps.<br> for (int i = 0; i &lt; mCardModels.length; i++) {<br> new CardWorkerTask().execute(mCardModels[i]);<br> }<br> }<br> /**<br> * Drawing implementation to draw all the cards completely .<br> */<br> protected void onDraw(Canvas canvas) {<br> super.onDraw(canvas);<br> // Don&#39;t draw anything until all the Asynctasks are done and all the Cards are ready.<br> if (mCardModels.length &gt; 0 &amp;&amp; mCards.size() == mCardModels.length) {<br> // Loop over all the cards, except the last one.<br> for (int i = 0; i &lt; mCards.size(); i++) {<br> // Each card is laid out a little to the right of the previous one.<br> mCardLeft = i * mCardSpacing;<br> drawCard(canvas, mCards.get(i), mCardLeft, 0);<br> }<br> }<br> // Invalidate the whole view. Doing this calls onDraw() if the view is visible.<br> invalidate();<br> }<br> /**<br> * Drawing implementation to draw one card<br> */<br> protected void drawCard(Canvas canvas, Card card, float left, float top) {<br> Paint paint = new Paint();<br> Bitmap bm = card.getBitmap();<br> CardModel cardModel = card.getCard();<br> // Draw outer rectangle.<br> paint.setAntiAlias(true);<br> paint.setColor(Color.WHITE);<br> paint.setStyle(Paint.Style.FILL);<br> Rect cardRect = new Rect(<br> (int)left,<br> (int)top,<br> (int)left + (int) card.getWidth(),<br> (int)top + (int) card.getHeight()<br> );<br> canvas.drawRect(cardRect, paint);<br> paint.setStyle(Paint.Style.STROKE);<br> paint.setColor(Color.DKGRAY);<br> canvas.drawRect(cardRect, paint);<br> canvas.drawBitmap(<br> bm,<br> (cardRect.left + (card.getWidth() / 2)) - (bm.getWidth() / 2),<br> (cardRect.top + (int) card.getHeaderHeight() + (card.getBodyHeight() / 2)<br> - (bm.getHeight() / 2)),<br> null<br> );<br> paint.setTextSize(card.getTitleSize());<br> paint.setColor(getResources().getColor(cardModel.getColor()));<br> paint.setStyle(Paint.Style.STROKE);<br> int titleLeftOffset = cardRect.left + (int) card.getTitleXOffset();<br> int titleTopOffset = cardRect.top + (int) card.getTitleYOffset() +<br> (int) card.getTitleSize();<br> canvas.drawText(cardModel.getName(), titleLeftOffset, titleTopOffset, paint);<br> }<br> /**<br> * converts drawable resource to bitmap<br> */<br> public Bitmap makeBitmap(Resources res, int resId, int reqWidth) {<br> // First decode with inJustDecodeBounds=true to check dimensions<br> final BitmapFactory.Options options = new BitmapFactory.Options();<br> options.inJustDecodeBounds = true;<br> BitmapFactory.decodeResource(res, resId, options);<br> // Calculate inSampleSize.<br> options.inSampleSize = calculateInSampleSize(options, reqWidth);<br> // Decode bitmap with inSampleSize set.<br> options.inJustDecodeBounds = false;<br> // Decode bitmap.<br> return BitmapFactory.decodeResource(res, resId, options);<br> }<br> /**<br> * Returns a bitmap scaled to the mentioned width.<br> */<br> private Bitmap getScaledBitmap(Bitmap bitmap, float width) {<br> float scale = width / bitmap.getWidth();<br> return Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scale),<br> (int) (bitmap.getHeight() * scale), false);<br> }<br> /**<br> * this methods subsamples the original size image to a smaller image as per the requirement. This saves memory.<br> */<br> private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth) {<br> // Get the raw width of image.<br> final int width = options.outWidth;<br> int inSampleSize = 1;<br> // Calculate the best inSampleSize.<br> if (width &gt; reqWidth) {<br> final int halfWidth = width / 2;<br> while ((halfWidth / inSampleSize) &gt; reqWidth) {<br> inSampleSize *= 2;<br> }<br> }<br> return inSampleSize;<br> }<br> /**<br> * Async task which downloads bitmap on another thread and create cards out of it<br> */<br> class CardWorkerTask extends AsyncTask&lt;CardModel, Void, Bitmap&gt; {<br> CardModel cardModel;<br> private final WeakReference&lt;ArrayList&lt;Card&gt;&gt; mCardsReference;<br> public CardWorkerTask() {<br> mCardsReference = new WeakReference&lt;ArrayList&lt;Card&gt;&gt;(mCards);<br> }<br> @Override<br> protected Bitmap doInBackground(CardModel… params) {<br> cardModel = params[0];<br> //<br> return getScaledBitmap(<br> makeBitmap(getResources(), cardModel.getAvatarId(), (int) mImageWidth),<br> mImageWidth<br> );<br> }<br> /**<br> * Adds cards created using bitmap fetched<br> */<br> @Override<br> protected void onPostExecute(Bitmap bitmap) {<br> // Check that the list and bitmap are not null.<br> if (mCardsReference != null &amp;&amp; bitmap != null) {<br> // Create a new Card.<br> mCards.add(new Card(cardModel, bitmap));<br> }<br> }<br> }<br>}</pre><p><em>Code 24. UnoptimizedCardsView.java</em></p><h4>4.2.5 OptimizedCardsView.java with only drawing of visible parts of the cards</h4><pre>package com.example.perforamancetest.overdraw_custom_view;<br>import android.content.Context;<br>import android.content.res.Resources;<br>import android.graphics.Bitmap;<br>import android.graphics.BitmapFactory;<br>import android.graphics.Canvas;<br>import android.graphics.Color;<br>import android.graphics.Paint;<br>import android.graphics.Rect;<br>import android.os.AsyncTask;<br>import android.view.View;<br>import java.lang.ref.WeakReference;<br>import java.util.ArrayList;<br>/**<br>* A custom view that presents a stacked overlapping collection of cards. OnDraw method draws only the portion<br>* of the card that is visible on the screen<br>*/<br>class OptimizedCardsView extends View {<br> /**<br> * Array of cards to be displayed in the view.<br> */<br> private CardModel[] mCardModels;<br> /**<br> * The width of the card that needs to be shown<br> */<br> float mImageWidth;<br> /**<br> * THe difference in left edge positions of two consecutive image cards.<br> */<br> protected float mCardSpacing;<br> /**<br> * The position of the left edge of each card in the view<br> */<br> private float mCardLeft;<br> /**<br> * List of cards which needs to be shown in the view<br> */<br> private ArrayList&lt;Card&gt; mCards = new ArrayList&lt;Card&gt;();<br> /**<br> *<br> * @param context application context .<br> * @param cardModels card models for each card to be displayed.<br> * @param imageWidth The width of each card which is shown<br> * @param cardSpacing The difference in left edge positions of two consecutive image cards.<br> */<br> public OptimizedCardsView(Context context, CardModel[] cardModels, float imageWidth,<br> float cardSpacing) {<br> super(context);<br> mCardModels = cardModels;<br> mImageWidth = imageWidth;<br> mCardSpacing = cardSpacing;<br> // Fire AsyncTasks to fetch and scale the bitmaps.<br> for (int i = 0; i &lt; mCardModels.length; i++) {<br> new CardWorkerTask().execute(mCardModels[i]);<br> }<br> }<br> /**<br> * Drawing implementation to draw all the cards completely .<br> */<br> protected void onDraw(Canvas canvas) {<br> // Don&#39;t draw anything until all the Asynctasks are done and all the DroidCards are ready.<br> if (mCardModels.length &gt; 0 &amp;&amp; mCards.size() == mCardModels.length) {<br> // Loop over all the droids, except the last one.<br> int i;<br> for (i = 0; i &lt; mCards.size() - 1; i++) {<br> // Each card is laid out a little to the right of the previous one.<br> mCardLeft = i * mCardSpacing;<br> // Save the canvas state.<br> canvas.save();<br> // Restrict the drawing area to only what will be visible.<br> canvas.clipRect(<br> mCardLeft,<br> 0,<br> mCardLeft + mCardSpacing,<br> mCards.get(i).getHeight()<br> );<br> // Draw the card. Only the parts of the card that lie within the bounds defined by<br> // the clipRect() get drawn.<br> drawCard(canvas, mCards.get(i), mCardLeft, 0);<br> // Revert canvas to non-clipping state.<br> canvas.restore();<br> }<br> // Draw the final card. This one doesn&#39;t get clipped.<br> drawCard(canvas, mCards.get(mCards.size() - 1),<br> mCardLeft + mCardSpacing, 0);<br> }<br> // Invalidate the whole view. Doing this calls onDraw() if the view is visible.<br> invalidate();<br> }<br> /**<br> * Drawing implementation to draw one card<br> */<br> protected void drawCard(Canvas canvas, Card card, float left, float top) {<br> Paint paint = new Paint();<br> Bitmap bm = card.getBitmap();<br> CardModel cardModel = card.getCard();<br> // Draw outer rectangle.<br> paint.setAntiAlias(true);<br> paint.setColor(Color.WHITE);<br> paint.setStyle(Paint.Style.FILL);<br> Rect cardRect = new Rect(<br> (int)left,<br> (int)top,<br> (int)left + (int) card.getWidth(),<br> (int)top + (int) card.getHeight()<br> );<br> canvas.drawRect(cardRect, paint);<br> paint.setStyle(Paint.Style.STROKE);<br> paint.setColor(Color.DKGRAY);<br> canvas.drawRect(cardRect, paint);<br> canvas.drawBitmap(<br> bm,<br> (cardRect.left + (card.getWidth() / 2)) - (bm.getWidth() / 2),<br> (cardRect.top + (int) card.getHeaderHeight() + (card.getBodyHeight() / 2)<br> - (bm.getHeight() / 2)),<br> null<br> );<br> paint.setTextSize(card.getTitleSize());<br> paint.setColor(getResources().getColor(cardModel.getColor()));<br> paint.setStyle(Paint.Style.STROKE);<br> int titleLeftOffset = cardRect.left + (int) card.getTitleXOffset();<br> int titleTopOffset = cardRect.top + (int) card.getTitleYOffset() +<br> (int) card.getTitleSize();<br> canvas.drawText(cardModel.getName(), titleLeftOffset, titleTopOffset, paint);<br> }<br> /**<br> * converts drawable resource to bitmap<br> */<br> public Bitmap makeBitmap(Resources res, int resId, int reqWidth) {<br> // First decode with inJustDecodeBounds=true to check dimensions<br> final BitmapFactory.Options options = new BitmapFactory.Options();<br> options.inJustDecodeBounds = true;<br> BitmapFactory.decodeResource(res, resId, options);<br> // Calculate inSampleSize.<br> options.inSampleSize = calculateInSampleSize(options, reqWidth);<br> // Decode bitmap with inSampleSize set.<br> options.inJustDecodeBounds = false;<br> // Decode bitmap.<br> return BitmapFactory.decodeResource(res, resId, options);<br> }<br> /**<br> * Returns a bitmap scaled to the mentioned width.<br> */<br> private Bitmap getScaledBitmap(Bitmap bitmap, float width) {<br> float scale = width / bitmap.getWidth();<br> return Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scale),<br> (int) (bitmap.getHeight() * scale), false);<br> }<br> /**<br> * this methods subsamples the original size image to a smaller image as per the requirement. This saves memory.<br> */<br> private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth) {<br> // Get the raw width of image.<br> final int width = options.outWidth;<br> int inSampleSize = 1;<br> // Calculate the best inSampleSize.<br> if (width &gt; reqWidth) {<br> final int halfWidth = width / 2;<br> while ((halfWidth / inSampleSize) &gt; reqWidth) {<br> inSampleSize *= 2;<br> }<br> }<br> return inSampleSize;<br> }<br> /**<br> * Async task which downloads bitmap on another thread and create cards out of it<br> */<br> class CardWorkerTask extends AsyncTask&lt;CardModel, Void, Bitmap&gt; {<br> CardModel cardModel;<br> private final WeakReference&lt;ArrayList&lt;Card&gt;&gt; mCardsReference;<br> public CardWorkerTask() {<br> mCardsReference = new WeakReference&lt;ArrayList&lt;Card&gt;&gt;(mCards);<br> }<br> @Override<br> protected Bitmap doInBackground(CardModel… params) {<br> cardModel = params[0];<br> //<br> return getScaledBitmap(<br> makeBitmap(getResources(), cardModel.getAvatarId(), (int) mImageWidth),<br> mImageWidth<br> );<br> }<br> /**<br> * Adds cards created using bitmap fetched<br> */<br> @Override<br> protected void onPostExecute(Bitmap bitmap) {<br> // Check that the list and bitmap are not null.<br> if (mCardsReference != null &amp;&amp; bitmap != null) {<br> // Create a new Card.<br> mCards.add(new Card(cardModel, bitmap));<br> }<br> }<br> }<br>}</pre><p><em>Code 25. OptimizedCardsView.java</em></p><h3>4.3 Tool Test</h3><h4>4.3.1 LayoutInspector Tool Test</h4><p><strong>4.3.1.1 LayoutInspector on UnoptimizedCardView.java</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YqyYVfzEZLUhLe78" /></figure><p><em>Figure 86. LayoutInspector result for UnoptimizedCardView.java</em></p><p><strong>4.3.1.2 LayoutInspector on OptimizedCardView.java</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y3QSepGo7PjfIEh1" /></figure><p><em>Figure 87. LayoutInspector result for UnoptimizedCardView.java</em></p><p><strong>4.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from the component tree of Figure 86 and Figure 87 that the layout hierarchy for UnOptimizedCardsView.java and OptimizedCardsView.java is the same.</p><p>This indicates LayoutInspector is ineffective in detecting any UI performance degradation due to CustomView Overdrawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8sWCwU9vC7ewfl3J1QlaA.png" /></figure><p><em>Table 25. : Table of results of Layout Inspector tool test on UnOptimizedCardsView.java and OptimizedCardsView.java</em></p><h4>4.4.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>4.4.3.2.1 Debug GPU Overdraw on RecyclerView with expensive onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*X4a26aC9gk-_tKQa" /></figure><p><em>Figure 88. Debug Gpu overdraw result for UnOptimizedCardsView.java</em></p><p><strong>4.4.3.2.2 Debug GPU Overdraw on RecyclerView with efficient onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*TNCc5lrODx5qNFaV" /></figure><p><em>Figure 89. Debug Gpu overdraw result for OptimizedCardsView.java</em></p><p><strong>4.4.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of UnOptimizedView(Figure 88) and OptimizedView(Figure 89) that Debug GPU overdraw tool clearly highlights inefficient draw operations in UnoptimizedView where drawing for invisible sections of the cards is also done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dErI6MlDGYpeGs9uLZmCOA.png" /></figure><p><em>Table 26. Table of results of Debug GPU overdraw tool test on UnOptimizedCardsView.java and OptimizedCardsView.java</em></p><h4>4.4.3.3 Profile GPU rendering Tool Test</h4><p><strong>4.4.3.3.1 Profile GPU rendering on UnOptimizedCardsView.java</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*OYWJQdR7BHRmtPX8" /></figure><p><em>Figure 90. Profile GPU rendering result for UnOptimizedCardsView.java</em></p><p><strong>4.4.3.3.2 Profile GPU rendering on OptimizedCardsView.java</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*WDvDDdNPiEcxLTRr" /></figure><p><em>Figure 91. Profile GPU rendering result for OptimizedCardsView.java</em></p><p><strong>4.4.3.2.3 Profil GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars of UnOptimizedCardsView.java ( Figure 90) and OptimizedCardsView.java(Figure 91) that the rendering bars with OptimizedCardsView are smaller in height than rendering bars with UnOptimizedCardsView. Moreover, the increase in height of rendering bars for UnOptimizedCardsView is primarily because of the red and orange lines. The red bars correspond to command issue which represents the time spent by Android’s 2D renderer issuing commands to OpenGL to draw and redraw display lists. The height of this bar is directly proportional to the sum of the time it takes each display list to execute — more display lists equals a taller red bar. The yellow bar correspond to Swap Buffers which represents the time the CPU is waiting for the GPU to finish its work. If this bar gets tall, it means the app is doing too much work on the GPU.</p><p>Above indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by custom view overdrawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCxRYKiCEGNj4d2PVZzRjg.png" /></figure><h4>4.4.3.4 Show View Updates Tool Test</h4><p><strong>4.4.3.4.1 Show View Updates for Custom View with Overdraw</strong></p><p>The result of applying Show View Updates developer option on Custom View with overdraw is shown in <a href="https://doi.org/10.5281/zenodo.7016696">Reference [27]</a></p><p><strong>4.4.3.4.2 Show View Updates for Custom View without Overdraw</strong></p><p>The result of applying Show View Updates developer option on Custom View without overdraw is shown in <a href="https://doi.org/10.5281/zenodo.7016703">Reference [28]</a></p><p><strong>4.4.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result for custom view with overdraw[27] and custom view without overdraw[28] that there is significant difference in results of applying this tool. The view updates slow down when custom view with overdraw is drawn. This indicates that the Show view updates tool is effective in detecting the rendering performance issues caused by overdrawing in custom views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7T6SKUJTvHdMrHcy2Vb_g.png" /></figure><h4>4.4.3.5 Android CPU Profiler Tool Test</h4><p>As part of this test, we will click on ‘Show Cards View’ button to inflate and add Cards View for both OptimizedCardsView and UnOptimizedCards. The state at the end of the test looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*A1eHRLHoLgBGwGvi" /></figure><p><em>Figure 92. The end state of clicking on ‘SHOW CARDS VIEW’ button.</em></p><p><strong>4.4.3.5.1 Android CPU Profiler tool test for UnOptimizedCardsView.java</strong><br><strong>4.4.3.5.1.1 System Trace CPU Profiler output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UBAA3OYcPnHs52q2" /></figure><p><em>Figure 93. The CPU profiler system trace visualization for UnOptimizedCardsView.java with overdraw of overlapped areas</em></p><p>Figure 93 presents that most of the frames are janky after rendering UnOptimizedCardsView.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T0ZZ3PiSg5KexwBe" /></figure><p><em>Figure 94. The CPU profiler system trace — All Frame visualization for UnOptimizedCardsView.java with overdraw of overlapped areas</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B8TinePvp-29r18S" /></figure><p><em>Figure 95. The CPU profiler system trace — Janky Frame visualization for UnOptimizedCardsView.java with overdraw of overlapped areas.</em></p><p>In Figure 95, it can be observed all the frames for UnOptimizedCardsView.java are janky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DULmWKd0kv69168W" /></figure><p><em>Figure 96. The CPU profiler system trace visualization for UnOptimizedCardsView with custom view overdrawing.</em></p><p>In Figure 96, It can be seen that all the jank frames are caused by multiple extended draw calls . This shows that the janks are caused primarily because of overdrawing which is needed to show all the overlapped cards completely</p><p><strong>4.4.3.5.2 Android CPU Profiler tool test for OptimizedCardsView.java</strong><br><strong>4.4.3.5.2.1 System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xJ9JR7k-_NcO2_79" /></figure><p><em>Figure 97. The CPU profiler system trace visualization for OptimizedCardsView.java without overdraw of overlapped areas</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ewv-7DPMy8yNjj2H" /></figure><p><em>Figure 98. The CPU profiler system trace — All Frame visualization for OptimizedCardsView.java without overdraw of overlapped areas.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dI63SNdOIPz8RZYf" /></figure><p><em>Figure 99. The CPU profiler system trace — Janky Frame visualization for for OptimizedCardsView.java without overdraw of overlapped areas.</em></p><p>From Figure 99, we see that there is no UI jank when OptimizedCardsView is rendered on the screen.</p><p><strong>4.4.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for UnOptimizedCardsView.java and OptimizedCardsView.java that there is significant reduction in number of jank frames itself by using clipRect() in drawing CustomViews to avoid overdrawing overlapped areas of custom views which are not shown on the screen. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by Custom View overdrawing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09-wxWmykGWa5YX0FicBzw.png" /></figure><p>This clearly shows that there is 100 percent improvement in number of jank frames by reducing the overdraw caused by complete drawing of overlapped cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2i8RhGHOjduWdCjRSROZyw.png" /></figure><h4>4.4.3.6 Tool Test Results on overdraw in custom views</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCQ4EjDKY0eXUkl4VYpbHw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81738dd99ec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3. Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/3-testing-the-effectiveness-of-different-android-tools-in-expensive-on-bind-call-in-recyclerview-25210e37f8b8?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/25210e37f8b8</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 04:52:20 GMT</pubDate>
            <atom:updated>2022-12-18T07:40:24.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>3. Testing the effectiveness of different Android Tools in detecting performance issues caused by Expensive on Bind Call in RecyclerView</h3><h3>3.1 Introduction</h3><p>Scrolling Lists in Android are normally implemented using the RecyclerView widget in android and are one of the most used android widgets to create the UI. Additionally, UI jank in scrollinglists is one of the most common UI jank issues that we can observe in Android[14].</p><h3>3.2 Code Implementation of Test</h3><p>RecyclerView contains two main methods as mentioned below :</p><ul><li><strong>public VH onCreateViewHolder (</strong><a href="https://developer.android.com/reference/android/view/ViewGroup.html"><strong>ViewGroup</strong></a><strong> parent, int viewType)</strong></li></ul><p>This is invoked when a new <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder">RecyclerView.ViewHolder</a> of the given type is needed to represent an item.</p><p>The new ViewHolder basically represents the new item view that needs to be created which can be created either by inflating an XML layout file or by manually inflating view in the code</p><ul><li><strong>public void onBindViewHolder (VH holder, int position, List&lt;Object&gt; payloads)</strong></li></ul><p>This is called when new data needs to be updated to display new data on item view at a particular position. This bind should ideally take less than 1 ms to run and needs to be very quick. It should only take a POJO class and bind that to the view without much manipulation so that the bind call is quick. This is called multiple times when scrolling in recycler view happens.</p><p>In order to test the effectiveness of different UI tools in detecting UI jank caused by expensive onBind call, we deliberately added a delay of 50 ms in onBind by using Thread.sleep() to simulate expensive work happening in the onBind() method. In order to verify that the UI jank is being caused by an expensive onBind() call, we repeat the application of different tools on an optimized onbind call, where we have removed Thread.sleep() statement.</p><h4>3.2.1 MainActivity.java</h4><pre>package com.example.perforamancetest<br>import android.os.Bundle<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.recyclerview.widget.LinearLayoutManager<br>import androidx.recyclerview.widget.RecyclerView<br>import com.example.perforamancetest.data.LocalDataSource<br>import com.example.performancetest.R<br>class MainActivity : AppCompatActivity() {<br> override fun onCreate(savedInstanceState: Bundle?) {<br> super.onCreate(savedInstanceState)<br> setContentView(R.layout.activity_main)<br> // Initialize data.<br> val myDataset = LocalDataSource().getMessages(this)<br> val recyclerView = findViewById&lt;RecyclerView&gt;(R.id.recycler_view)<br> recyclerView.layoutManager = LinearLayoutManager(this)<br> recyclerView.adapter = CustomAdapter(this, myDataset)<br><br> // Use this setting to improve performance if you know that changes<br> // in content do not change the layout size of the RecyclerView<br> recyclerView.setHasFixedSize(true)<br> }<br>}</pre><p><em>Code 15. MainActivity.java</em></p><h4>3.2.2 activity_main.xml</h4><pre>&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> tools:context=&quot;com.example.perforamancetest.MainActivity&quot;<br> android:background=&quot;#FFFFFF&quot;&gt;<br> &lt;androidx.recyclerview.widget.RecyclerView<br> android:id=&quot;@+id/recycler_view&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:scrollbars=&quot;vertical&quot;<br> app:layoutManager=&quot;LinearLayoutManager&quot; /&gt;<br>&lt;/FrameLayout&gt;</pre><p><em>Code 16. activity_main.xml</em></p><h4>3.2.3 CustomAdapter.java with expensive onBind method call</h4><pre>package com.example.perforamancetest;<br>import android.content.Context;<br>import android.view.LayoutInflater;<br>import android.view.View;<br>import android.view.ViewGroup;<br>import android.widget.TextView;<br>import androidx.recyclerview.widget.RecyclerView;<br>import com.example.performancetest.R;<br>import java.util.List;<br>public class CustomAdapter extends RecyclerView.Adapter&lt;CustomAdapter.ViewHolder&gt; {<br> private List&lt;String&gt; localDataSet;<br> /**<br> * Provide a reference to the type of views that you are using<br> * (custom ViewHolder).<br> */<br> public static class ViewHolder extends RecyclerView.ViewHolder {<br> private final TextView textView;<br> public ViewHolder(View view) {<br> super(view);<br> // Define click listener for the ViewHolder&#39;s View<br> textView = (TextView) view.findViewById(R.id.item_title);<br> }<br> public TextView getTextView() {<br> return textView;<br> }<br> }<br> /**<br> * Initialize the dataset of the Adapter.<br> *<br> * @param dataSet String[] containing the data to populate views to be used<br> * by RecyclerView.<br> */<br> public CustomAdapter(Context context, List&lt;String&gt; dataSet) {<br> localDataSet = dataSet;<br> }<br> // Create new views (invoked by the layout manager)<br> @Override<br> public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {<br> // Create a new view, which defines the UI of the list item<br> View view = LayoutInflater.from(viewGroup.getContext())<br> .inflate(R.layout.text_item, viewGroup, false);<br> return new ViewHolder(view);<br> }<br> // Replace the contents of a view (invoked by the layout manager)<br> @Override<br> public void onBindViewHolder(ViewHolder viewHolder, final int position) {<br> try {<br> Thread.sleep(50);<br> } catch (InterruptedException e) {<br> e.printStackTrace();<br> }<br> // Get element from your dataset at this position and replace the<br> // contents of the view with that element<br> viewHolder.getTextView().setText(localDataSet.get(position));<br> }<br> // Return the size of your dataset (invoked by the layout manager)<br> @Override<br> public int getItemCount() {<br> return localDataSet.size();<br> }<br>}</pre><p><em>Code 17. CustomAdapter.java with expensive onBind call</em></p><h4>3.2.4 CustomAdapter.java with optimized onBind method call</h4><pre>package com.example.perforamancetest;<br>import android.content.Context;<br>import android.view.LayoutInflater;<br>import android.view.View;<br>import android.view.ViewGroup;<br>import android.widget.TextView;<br>import androidx.recyclerview.widget.RecyclerView;<br>import com.example.performancetest.R;<br>import java.util.List;<br>public class CustomAdapter extends RecyclerView.Adapter&lt;CustomAdapter.ViewHolder&gt; {<br> private List&lt;String&gt; localDataSet;<br> /**<br> * Provide a reference to the type of views that you are using<br> * (custom ViewHolder).<br> */<br> public static class ViewHolder extends RecyclerView.ViewHolder {<br> private final TextView textView;<br> public ViewHolder(View view) {<br> super(view);<br> // Define click listener for the ViewHolder&#39;s View<br> textView = (TextView) view.findViewById(R.id.item_title);<br> }<br> public TextView getTextView() {<br> return textView;<br> }<br> }<br> /**<br> * Initialize the dataset of the Adapter.<br> *<br> * @param dataSet String[] containing the data to populate views to be used<br> * by RecyclerView.<br> */<br> public CustomAdapter(Context context, List&lt;String&gt; dataSet) {<br> localDataSet = dataSet;<br> }<br> // Create new views (invoked by the layout manager)<br> @Override<br> public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {<br> // Create a new view, which defines the UI of the list item<br> View view = LayoutInflater.from(viewGroup.getContext())<br> .inflate(R.layout.text_item, viewGroup, false);<br> return new ViewHolder(view);<br> }<br> // Replace the contents of a view (invoked by the layout manager)<br> @Override<br> public void onBindViewHolder(ViewHolder viewHolder, final int position) {<br> // try {<br> // Thread.sleep(50);<br> // } catch (InterruptedException e) {<br> // e.printStackTrace();<br> // }<br> // Get element from your dataset at this position and replace the<br> // contents of the view with that element<br> viewHolder.getTextView().setText(localDataSet.get(position));<br> }<br> // Return the size of your dataset (invoked by the layout manager)<br> @Override<br> public int getItemCount() {<br> return localDataSet.size();<br> }<br>}</pre><p><em>Code 18. CustomeAdapter.java with optimized onBind call</em></p><h4>3.2.5 text_item.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;TextView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> android:id=&quot;@+id/item_title&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:textColor=&quot;#000000&quot;<br> /&gt;</pre><p><em>Code 19. text_item.xml</em></p><h3>3.3 Tool Test</h3><h4>3.3.1 LayoutInspector Tool Test</h4><p><strong>3.3.1.1 LayoutInspector on RecyclerView with expensive onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xH397ONZsUwS18Iz" /></figure><p><em>Figure 73. LayoutInspector result for MainActivity.java with unoptimized onBind call</em></p><p><strong>3.3.1.2 LayoutInspector on RecyclerView with optimized onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dWU7205hyYu2F_-G" /></figure><p><em>Figure 74. LayoutInspector result for MainActivity with optimized onBind call</em></p><p><strong>3.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from the component tree of Figure 73 and Figure 74 that the layout hierarchy for FibonacciActivity remains the same irrespective of whether Fibonacci is being computed on the main thread or a separate thread.</p><p>This indicates LayoutInspector is ineffective in detecting any UI jank due to heavy computation on the main thread</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aRqePPQ7xLLKhVmiXrOpQ.png" /></figure><h4>3.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>3.3.2.1 Debug GPU Overdraw on RecyclerView with unoptimized onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*iKZO9MdRujklkGYt" /></figure><p><em>Figure 75. Debug GPU overdraw result for MainActivity with unoptimized onBind call</em></p><p><strong>3.3.2.2 Debug GPU Overdraw on RecyclerView with optimized onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*a28hD4FblEEWb9hF" /></figure><p><em>Figure 76. Debug GPU overdraw result for MainActivity with optimized onBind call</em></p><p><strong>3.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of MainActivity with an unoptimized onBind recycler view call(Figure 75) and with an optimized onBind recycler view call(Figure 76) that there is no difference in output given by Debug GPU overdraw developer option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ccGMBXEwaSQTEc8JNAQOw.png" /></figure><h4>3.3.3 Profile GPU rendering Tool Test</h4><p><strong>3.3.3.1 Profile GPU rendering on RecyclerView with unoptimized onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*iQYIc-5EmI6Tdde_" /></figure><p><em>Figure 77. Profile GPU rendering result for MainActivity with unoptimized onBind reyclerview call</em></p><p><strong>3.3.3.2 Profile GPU rendering on RecyclerView with optimized onBind call</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*PCOQ_CaD0ux1Ak7V" /></figure><p><em>Figure 78. Profile GPU rendering result for MainActivity with optimized onBind call</em></p><p><strong>3.3.2.3 Profil GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars of Main Activity with unoptimized onBind call ( Figure 77) and optimized onBind call(Figure 78) that the rendering bars with optimized onBind recyclerview call are smaller in height than rendering bars with unoptimized onBind recyclerview call. This indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by expensive onBind recyclerview call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9GzFvNBsy_p81-_OhR78A.png" /></figure><h4>3.3.4 Show View Updates Tool Test</h4><p><strong>3.3.4.1 Show View Updates on RecyclerView with unoptimized onBind call</strong></p><p>The result of applying Show View Updates developer option on FibonacciActivity with Fibonacci Computation on main thread is shown in <a href="https://doi.org/10.5281/zenodo.7013316">Reference [23]</a></p><p><strong>3.3.4.2 Show View Updates on RecyclerView with optimized onBind call</strong></p><p>The result of applying Show View Updates developer option on FibonacciActivity with Fibonacci Computation on separate thread is shown in <a href="https://doi.org/10.5281/zenodo.7013320">Reference [24]</a></p><p><strong>3.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result for Main Activity with expensive onBind recyclerview call[23] and optimized onBind recyclerview call[24] that there is significant difference in results of applying this tool. The view updates slow down when scrolling is done on recyclerview with unoptimized onBind call. This indicates that the Show view updates tool is effective in detecting the rendering performance issues caused by expensive onBind calls in recyclerview .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oquRKeSvH4muxI18Wgyb_w.png" /></figure><h4>3.3.5 Android CPU Profiler Tool Test</h4><p>As part of this test, we will scroll the recyclerview till mid of second item in both the cases: with thread sleep statement in onBind call and without thread sleep statement in on Bind call. The state at the end of the test looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*kZk-_gNIvx6vmabe" /></figure><p><em>Figure 79. The end state of scroll state on recyclerview to test expensive onBind call.</em></p><p><strong>3.3.5.1 Android CPU Profiler tool test for expensive onBind call in recyclerview</strong><br><strong>3.3.5.1.1 System Trace CPU Profiler output for unoptimized onBind call in recyclerview</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gwXI5Hh3nzzQK3Z3" /></figure><p><em>Figure 80. The CPU profiler system trace visualization for expensive onBind call in recyclerview</em></p><p>Figure 80 presents three major jank frames during recycler scroll. In order to inspect further, we explore all frame track for systrace in CPU profiler in figure 80</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m00z_0f8CHc_uo-F" /></figure><p><em>Figure 81. The CPU profiler system trace — All Frame visualization for scrolling on recyclerview with expensive onBind call</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*y39Qglb_wzzHMQVk" /></figure><p><em>Figure 82. The CPU profiler system trace — Janky Frame visualization for scrolling on recyclerview with expensive onBind call.</em></p><p>In Figure 82, it can be observed three jank frames during scrolling on recyclerview.</p><p><strong>3.3.5.2 Android CPU Profiler tool test for optimized onBind call in recyclerview</strong><br><strong>3.3.5.2.1 System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EkhJxMhpFfnXBzjG" /></figure><p><em>Figure 83. The CPU profiler system trace visualization for recyclerview scroll with optimized onBind call</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*juXMyOCU8Hs2qmQy" /></figure><p><em>Figure 84. The CPU profiler system trace — All Frame visualization for recyclerview scroll with optimized onBind call. This window shows all frames created in the current system trace recording.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l8wIVKOlxpYJKcxK" /></figure><p><em>Figure 85. The CPU profiler system trace — Janky Frame visualization for recyclerview scroll with optimized onBind call. This window shows none of the frames is janky.</em></p><p>From Figure 85, we see that there is no UI jank when scrolling is done on recyclerview with optimized onBind call.</p><p><strong>3.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for expensive and optimized onBind call in recyclerview scroll that there is a significant reduction in the number of jank frames itself by using optimizing the onBind call to take less time. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by running expensive operations in onBind call in recyclerview scroll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUu3AxdRZ6jCKdjvIx5Pew.png" /></figure><p>This clearly shows that there is a 100 percent improvement in the number of jank frames by using a separate thread for heavy computation tasks rather than running on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgBIHy3hOEU6TR_wicCdbw.png" /></figure><h4>3.3.6 Tool Test Results on unoptimized onBind call in recyclerview</h4><p>Tool used</p><p>Can detect rendering issues caused by unoptimized on bind call in recyclerview ?</p><p>If it is known that there is some UI jank or rendering performance issue, can this tool attribute the performance issue to unoptimized on bind call in recyclerview?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5umLH09PVfRGKwsZZq1-Kg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25210e37f8b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2. Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/4-2-fibonacci-computation-on-main-thread-a4d4a6adbfc7?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d4a6adbfc7</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 04:02:17 GMT</pubDate>
            <atom:updated>2022-12-18T04:56:24.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>2. Testing the effectiveness of different Android Tools in detecting performance issues caused by Android Fibonacci Computation on Main Thread</h3><h3>2.1 Introduction</h3><p>The main Thread is responsible for rendering the ui on the screen as well as handling the user input. If an expensive computation is done on the main thread, the main thread will remain busy in the computation and will be unresponsive till the computation is completed. This is a very common cause of UI Jank</p><h3>2.2 Code Implementation of Test</h3><p>As part of testing the effectiveness of different tools in detecting UI jank caused by heavy computation on the main thread, we created a test application where we compute the Fibonacci series on the main thread[21]. This operation is quite expensive and blocks the main thread for a considerable period of time. To verify that the tool test results are correct in pinpointing the real cause of UI jank in this case( which is running a heavy computation on the main thread), we ran the same tools with Fibonacci computation on a separate thread using AsyncTask[22].</p><p>The Fibonacci Activity ( Code 12 ) consists of a gif of an animated dancing cartoon. At the launch of the activity, the animation is clearly visible smoothly. When a user clicks on ‘Compute Some Fibonacci Numbers’ on the screen, the Fibonacci series computation starts. In one case computation happens on the main thread and on another, computation happens on a separate Async task thread. When the Fibonacci series is being computed, the main thread is completely occupied with computation and the animation is stalled momentarily as the animation also runs on the main thread. In the next sections, we will apply different tools to check their effectiveness in detecting UI jank caused by heavy computation on the main thread and separate thread.</p><h4>2.2.1 LauncherActivity.java</h4><pre>package com.example.perforamancetest;<br>import android.app.Activity;<br>import android.content.Intent;<br>import android.os.Bundle;<br>import android.view.ViewGroup;<br>import android.widget.Button;<br>import com.example.performancetest.R;<br>public class LauncherActivity extends Activity {<br> @Override<br> protected void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.launcher_main);<br> ViewGroup rootView = (ViewGroup) findViewById(R.id.main_rootview);<br> addButton(&quot;Fibonacci Test&quot;, rootView);<br> }<br> public void addButton( String description, ViewGroup parent) {<br> Button button = new Button(this);<br> button.setOnClickListener(v -&gt; {<br> Intent problemIntent = new Intent(LauncherActivity.this, FibonacciActivity.class);<br> startActivity(problemIntent);<br> });<br> button.setText(description);<br> parent.addView(button);<br> }<br>}</pre><p><em>Code 10. LauncherActivity.java</em></p><h4>2.2.2 launcher_main.xml</h4><pre>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:orientation=&quot;vertical&quot;<br> android:id=&quot;@+id/main_rootview&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br> android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br> tools:context=&quot;com.example.perforamancetest.LauncherActivity&quot;<br> tools:ignore=&quot;MergeRootFrame&quot; /&gt;</pre><p><em>Code 11. launcher_main.xml</em></p><h4>2.2.3 FibonacciActivity.java with computeFibnocci on the main thread</h4><pre>package com.example.perforamancetest;<br>import android.app.Activity;<br>import android.os.Bundle;<br>import android.os.Debug;<br>import android.util.Log;<br>import android.view.View;<br>import android.webkit.WebView;<br>import android.widget.Button;<br>import com.example.performancetest.R;<br><br>public class FibonacciActivity extends Activity {<br> public static final String LOG_TAG = &quot;CachingActivityExercise&quot;;<br> @Override<br> protected void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.activity_fibonacci);<br> Button theButtonThatDoesFibonacciStuff = (Button) findViewById(R.id.caching_do_fib_stuff);<br> theButtonThatDoesFibonacciStuff.setText(&quot;Compute some Fibonacci numbers.&quot;);<br> theButtonThatDoesFibonacciStuff.setOnClickListener(new View.OnClickListener() {<br> @Override<br> public void onClick(View v) {<br> <br> // Compute the 40th number in the fibonacci sequence, then dump to log output. Note<br> // how the UI hangs each time you do this.<br> Log.i(LOG_TAG, String.valueOf(computeFibonacci(30)));<br> <br> }<br> });<br> // It&#39;s much easier to see how your decisions affect framerate when there&#39;s something<br> // changing on screen. For entirely serious, educational purposes, a dancing pirate<br> // will be included with this exercise.<br> WebView webView = (WebView) findViewById(R.id.webview);<br> webView.getSettings().setUseWideViewPort(true);<br> webView.getSettings().setLoadWithOverviewMode(true);<br> webView.loadUrl(&quot;file:///android_asset/dancing_cartoon.gif&quot;);<br> }<br> /**<br> * Why store things when you can recurse instead? Don&#39;t let evidence, personal experience,<br> * or rational arguments from your peers fool you. The elegant solution is the best solution.<br> *<br> * @param positionInFibSequence The position in the fibonacci sequence to return.<br> * @return the nth number of the fibonacci sequence. Seriously, try to keep up.<br> */<br> public int computeFibonacci(int positionInFibSequence) {<br> if (positionInFibSequence &lt;= 2) {<br> return 1;<br> } else {<br> return computeFibonacci(positionInFibSequence - 1)<br> + computeFibonacci(positionInFibSequence - 2);<br> }<br> }<br>}</pre><p><em>Code 12. FibonacciActivity.java</em></p><h4>2.2.4 FibonacciActivity.java with computeFibnocci on a separate thread</h4><pre>package com.example.perforamancetest;<br>import android.app.Activity;<br>import android.os.AsyncTask;<br>import android.os.Bundle;<br>import android.os.Debug;<br>import android.util.Log;<br>import android.view.View;<br>import android.webkit.WebView;<br>import android.widget.Button;<br>import com.example.performancetest.R;<br><br>public class FibonacciActivity extends Activity {<br> public static final String LOG_TAG = &quot;CachingActivityExercise&quot;;<br> @Override<br> protected void onCreate(Bundle savedInstanceState) {<br> super.onCreate(savedInstanceState);<br> setContentView(R.layout.activity_fibonacci);<br> Button theButtonThatDoesFibonacciStuff = (Button) findViewById(R.id.caching_do_fib_stuff);<br> theButtonThatDoesFibonacciStuff.setText(&quot;Compute some Fibonacci numbers.&quot;);<br> theButtonThatDoesFibonacciStuff.setOnClickListener(new View.OnClickListener() {<br> @Override<br> public void onClick(View v) {<br> // Compute the 40th number in the fibonacci sequence, then dump to log output. Note<br> // how the UI hangs each time you do this.<br> new FibonacciAsyncTask().execute(30);<br> }<br> });<br> // It&#39;s much easier to see how your decisions affect framerate when there&#39;s something<br> // changing on screen. For entirely serious, educational purposes, a dancing pirate<br> // will be included with this exercise.<br> WebView webView = (WebView) findViewById(R.id.webview);<br> webView.getSettings().setUseWideViewPort(true);<br> webView.getSettings().setLoadWithOverviewMode(true);<br> webView.loadUrl(&quot;file:///android_asset/dancing_cartoon.gif&quot;);<br> }<br> /**<br> * Optimized Fibonacci Code<br> */<br><br> private class FibonacciAsyncTask extends AsyncTask&lt;Integer,Void,Integer&gt;{<br> int[] fibonacciList ;<br> @Override<br> protected void onPreExecute() {<br> super.onPreExecute();<br> }<br> @Override<br> protected Integer doInBackground(Integer… integers) {<br> return computeFibonacci(integers[0]);<br> }<br> @Override<br> protected void onPostExecute(Integer integer) {<br> super.onPostExecute(integer);<br> Log.i(LOG_TAG, String.valueOf(integer));<br> }<br> public int computeFibonacci(int positionInFibSequence) {<br> if(fibonacciList == null){<br> fibonacciList = new int[positionInFibSequence+1];<br> }<br> if(positionInFibSequence==0){<br> return 0;<br> }<br> else if(positionInFibSequence ==1){<br> return 1;<br> }<br> else if(fibonacciList[positionInFibSequence]==0){<br> fibonacciList[positionInFibSequence]= computeFibonacci(positionInFibSequence-1)+computeFibonacci(positionInFibSequence-2);<br> }<br> return fibonacciList[positionInFibSequence];<br> }<br> }<br>}</pre><p><em>Code 13. FibonacciActivity.java</em></p><h4>2.2.5 activity_fibonacci.xml</h4><pre>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br> xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br> android:id=&quot;@+id/caching_rootview&quot;<br> android:orientation=&quot;vertical&quot;<br> android:layout_width=&quot;match_parent&quot;<br> android:layout_height=&quot;match_parent&quot;<br> android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br> android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br> android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br> tools:context=&quot;com.example.perforamancetest.FibonacciActivity&quot;&gt;<br> &lt;Button<br> android:layout_width=&quot;wrap_content&quot;<br> android:layout_height=&quot;wrap_content&quot;<br> android:id=&quot;@+id/caching_do_fib_stuff&quot; /&gt;<br> &lt;WebView<br> android:layout_width=&quot;300dp&quot;<br> android:layout_height=&quot;300dp&quot;<br> android:id=&quot;@+id/webview&quot;<br> android:layout_gravity=&quot;center_horizontal&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><p><em>Code 14. activity_fibonacci.xml</em></p><h3>2.3 Tool Test</h3><h4>2.3.1 LayoutInspector Tool Test</h4><p><strong>2.3.1.1 LayoutInspector on FibonacciActivity.java with Fibonacci Computation on the Main thread</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HXncHrM3ymoHTpcN" /></figure><p><em>Figure 58. LayoutInspector result for FibonacciActivity.java with Fibonacci Computation on the main thread</em></p><p><strong>2.3.1.2 LayoutInspector on FibonacciActivity.java with Fibonacci Computation on a separate thread</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJtQptMk8igMf5c2" /></figure><p><em>Figure 59. LayoutInspector result for FibonacciActivity.java with Fibonacci Computation on a separate thread</em></p><p><strong>2.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from the component tree of Figure 58 and Figure 59 that the layout hierarchy for FibonacciActivity remains the same irrespective of whether Fibonacci is being computed on the main thread or a separate thread .</p><p>This indicates LayoutInspector is ineffective in detecting any UI jank due to heavy computation on the main thread</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elP8EWIHZyMaN1oA3R1Bgg.png" /></figure><h4>2.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>2.3.2.1 Debug GPU Overdraw With Fibonacci Computation on the main thread</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*QiX0F1Y_zmbQzBAZ" /></figure><p><em>Figure 60. Debug GPU overdraw result for FibonacciActivity.java with Fibonacci Computation on the main thread</em></p><p><strong>2.3.2.2 Debug GPU Overdraw with Fibonacci Computation on a separate thread</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*YDg9Jy2nv_5Qe7jt" /></figure><p><em>Figure 61. Debug GPU overdraw result for FibonacciActivity.java with Fibonacci Computation on a separate thread</em></p><p><strong>2.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of FibonacciActivity with Fibonacci Computation on the main thread(Figure 60) and Fibonacci Computation on a separate thread(Figure 61) that there is no difference in output given by Debug GPU overdraw developer option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbtj1i3kMQYHqMDRJjkGKA.png" /></figure><h4>2.3.3 Profile GPU rendering Tool Test</h4><p><strong>2.3.3.1 Profile GPU rendering for FibonacciActivity.java with Fibonacci Computation on Main Thread</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*B5vXC0uQ1IDICEsa" /></figure><p><em>Figure 62. Debug GPU overdraw result for FibonacciActivity with Fibonacci Computation on Main Thread</em></p><p><strong>2.3.3.2 Profile GPU rendering for FibonacciActivity.java without Fibonacci Computation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*LOTEaiP4VjldNaO8" /></figure><p><em>Figure 63. Debug GPU overdraw result for FibonacciActivity with Fibonacci Computation on a separate thread</em></p><p><strong>2.3.2.3 Profile GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars of FibonacciActivity.java with Fibonacci computation on the main thread(Figure 62) and Fibonacci computation on the separate thread(Figure 63) that the rendering bars with Fibonacci Computation on the separate thread are smaller in height than rendering bars with Fibonacci computation on the main thread. This indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by heavy computation on the main thread.</p><p>Tool used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BPAalQyi2irarzXG4-t6w.png" /></figure><p><em>Table 13. Table of results of Profile GPU rendering tool test on FibonacciActivity.java with Fibonacci computation on the main thread</em></p><h4>2.3.4 Show View Updates Tool Test</h4><p><strong>2.3.4.1 Show View Updates for FibonacciActivity.java with Fibonacci Computation on Main Thread</strong></p><p>The result of applying the Show View Updates developer option on FibonacciActivity with Fibonacci Computation on the main thread is shown in <a href="https://doi.org/10.5281/zenodo.7012710">Reference [19]</a></p><p><strong>2.3.4.2 Show View Updates for FibonacciActivity.java with Fibonacci Computation on Separate Thread</strong></p><p>The result of applying the Show View Updates developer option on FibonacciActivity with Fibonacci Computation on a separate thread is shown in <a href="https://doi.org/10.5281/zenodo.7012716">Reference [20]</a></p><p><strong>2.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result for FibonacciActivity with Fibonacci Computation on the main thread[19] and Fibonacci Computation on a separate thread[20] that there is a significant difference in the results of applying this tool. The view updates stop when Fibonacci computation starts by pressing the button. This indicates that the Show view updates tool is effective in detecting the rendering performance issues caused by nested view hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bu4Ay9ReJb832akDloGICg.png" /></figure><h4>2.3.5 Android CPU Profiler Tool Test</h4><p><strong>2.3.5.1 Android CPU Profiler tool test for FibonacciActivity.java with Fibonacci Computation on the main thread</strong><br><strong>2.3.5.1.1 Android CPU Profiler tool test for FibonacciActivity.java with Fibonacci Computation on the main thread — System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/0*VWBXyDZxSER2KUGf" /></figure><p><em>Figure 64. The CPU profiler system trace visualization for FibonacciActivity with Fibonacci computation on the Main thread.</em></p><p>Figure 64 presents some recurring shorter jank frames which are primarily due to recurring steps in the dancing_cartoon animation. In order to focus on the Ui jank introduced with Fibonacci computation on the main thread, we only focus on the UI jank frame coinciding with the user input shown in the user track above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*4T5JFDXJ1UNZmAcN" /></figure><p><em>Figure 65. The CPU profiler system trace — All Frame visualization with Fibonacci Computation on the main thread. This window shows all frames created in the current system trace recording.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*p3RIt6vjdl9jzAO8" /></figure><p><em>Figure 66. The CPU profiler system trace — Janky Frame visualization with Fibonacci computation on the main thread. This window shows all janky frames created in the current system trace recording</em></p><p>In Figure 56, frame 878317 coincides with the user button click which starts Fibonacci computation. The other frames 878382, 878303, and 878462 are recurring jank frames. To keep ourselves focussed on the jank experience introduced only due to Fibonacci computation, we keep frame 878317 under consideration.</p><p>From Figure 64, It can be observed that the performance test thread ( thread corresponding to our application) is continuously green ( running) for the duration of frame 878317. This clearly gives an indication to look deeper into the application thread for the window when the button is clicked to see the activity on the thread that may be causing the UI jank.</p><p><strong>2.3.5.1.2 Android CPU Profiler tool test for FibonacciActivity.java with Fibonacci Computation on main thread — Java/Kotlin Method Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*Lv5y8SDf0DgZEUtC" /></figure><p><em>Figure 67. The CPU profiler kotlin/java method trace visualization for FibonacciActivity.java with Fibonacci computation. This window clearly shows that computeFibonacci function takes a lot of time to run after the button click happens. This is the same method that is written within the onClick handler.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*BJowLunxg4_tsTq8" /></figure><p><em>Figure 68. The CPU profiler kotlin/java method traces Top Down visualization for button click with Fibonacci computation on the main thread.</em></p><p>It can be clearly seen from Figure 68 that 99.99 percent of the time consumed in the onClick handler comes from running computeFibonacci on the main thread. This clearly indicates that running a heavy computation on the main thread is the main cause of extra UI jank on clicking the button which starts Fibonacci computation on the main thread.</p><p>This is additionally visible from the flame chart shown in figure 69.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/0*7QFE4PSjqyUPBByr" /></figure><p><em>Figure 69. The CPU profiler kotlin/java method traces Flame chart visualization for onClick on FibonacciActivity with Fibonacci computation on the main thread.</em></p><p><strong>2.3.5.2 Android CPU Profiler tool test for FibonacciActivity.java with Fibonacci Computation on separate thread4.2.3.5.2.1 Android CPU Profiler tool test for FibonacciActivity.java with Fibonacci Computation on a separate thread- System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*kVybjBiiN7QbPukD" /></figure><p><em>Figure 70. The CPU profiler system trace visualization for fibonacciActivity with Fibonacci computation on Async task. This window clearly shows no jank frame. This also shows a lot of computation is done on AsyncTask at the bottom of the screenshot</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*1YaAJ5KoxgXTxNgp" /></figure><p><em>Figure 71. The CPU profiler system trace — All Frame visualization for Fibonacci computation on async task. This window shows all frames created in the current system trace recording.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*jmzzNdMtmeBhByjR" /></figure><p><em>Figure 72. The CPU profiler system trace — Janky Frame visualization for Fibonacci computation on a separate thread. This window shows none of the frames is janky.</em></p><p>From Figure 72, we see that there is no UI jank when Fibonacci computation is done on a separate thread.</p><p><strong>2.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for Fibonacci computation on the main thread and separate thread that there is a significant reduction in the number of janks frames itself by using running computation on separate thread rather than running on the main thread. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by running a heavy computation on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49mzXK4DmZLLtW_az4OOLQ.png" /></figure><p>This clearly shows that there is a 100 percent improvement in the number of jank frames by using a separate thread for heavy computation tasks rather than running on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rq3GSEpRK4GAQ5Khlwwlug.png" /></figure><h4>2.3.6 Tool Test Results on expensive operations running on the main thread</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTYzzhw9rxnCcznED5k4-w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4d4a6adbfc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1. Testing the effectiveness of different Android Tools in detecting performance issues caused by…]]></title>
            <link>https://er-abhishek-luthra.medium.com/1-testing-the-effectiveness-of-different-android-tools-in-testing-nestedviewhierarchy-issues-on-45493f49c33c?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/45493f49c33c</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-tools]]></category>
            <category><![CDATA[android-profiler]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-performance]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 10:21:18 GMT</pubDate>
            <atom:updated>2022-12-18T10:16:03.430Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Testing the effectiveness of different Android Tools in detecting performance issues caused by NestedViewHierarchy issues on Android</h3><h3>1.1 Introduction</h3><p>There are multiple phases of measure, layout and draw involved in rendering views on the device screen. Every phase requires top-down traversal of the view tree. Therefore, the more a layout is nested and the more is the height of the view hierarchy, the more computation power will be needed in rendering the layout. If the layout can be flattened out without changing the final appearance of the UI to the screen, it can help reduce the computation power needed to render the layout and can free out the main thread for other important tasks.</p><h3>1.2 Code Implementation of Test</h3><p>As part of testing the effectiveness of different tools on the nested view hierarchy problem, we created two layouts with the same visual appearance as can be seen in Figure 36 and Figure 37. One layout(Code 8) is nested and is created using LinearLayout and RelativeLayout. The other layout(Code 9) is created using constraint layout and is non-nested.</p><h4>1.2.1 NestedViewHierarchyTestActivty.java</h4><pre>package com.example.perforamancetest.nestedviewhierarchy<br><br>import android.annotation.SuppressLint<br>import android.os.AsyncTask<br>import android.os.Bundle<br>import android.os.Handler<br>import android.util.Log<br>import android.view.FrameMetrics<br>import android.view.View<br>import android.view.ViewGroup<br>import android.view.Window<br>import android.widget.Button<br>import android.widget.TextView<br>import androidx.appcompat.app.AppCompatActivity<br>import com.example.nestedviewoverdraw.R<br>import java.lang.ref.WeakReference<br><br>class NestedViewHierarchyTestActivty : AppCompatActivity() {<br><br>   private val frameMetricsHandler = Handler()<br><br>   private val frameMetricsListener = Window.OnFrameMetricsAvailableListener {<br>           _, frameMetrics, _ -&gt;<br>       val frameMetricsCopy = FrameMetrics(frameMetrics)<br>       // Layout measure duration in Nano seconds<br>       val layoutMeasureDurationNs = frameMetricsCopy.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION)<br><br>       Log.d(TAG, &quot;layoutMeasurementDurationNs: &quot; + layoutMeasureDurationNs)<br>   }<br><br>   override fun onCreate(savedInstanceState: Bundle?) {<br>       super.onCreate(savedInstanceState)<br>       setContentView(R.layout.activity_nested_view_hierarchy)<br><br>       val traditionalNestedCalcButton = findViewById&lt;Button&gt;(R.id.button_start_calc_traditional)<br>       val constraintNonNestedCalcButton = findViewById&lt;Button&gt;(R.id.button_start_calc_constraint)<br>       val textViewFinish = findViewById&lt;TextView&gt;(R.id.textview_finish)<br>       traditionalNestedCalcButton.setOnClickListener {<br>           @SuppressLint(&quot;InflateParams&quot;)<br>           constraintNonNestedCalcButton.visibility = View.INVISIBLE<br>           val container = layoutInflater<br>               .inflate(R.layout.activity_nested_traditional, null) as ViewGroup<br>           val measurementAsyncTask = MeasurementLayoutAsyncTask(<br>               getString(R.string.executing_nth_iteration),<br>               WeakReference(traditionalNestedCalcButton),<br>               WeakReference(textViewFinish),<br>               WeakReference(container))<br>           measurementAsyncTask.execute()<br>       }<br><br>       constraintNonNestedCalcButton.setOnClickListener {<br>           @SuppressLint(&quot;InflateParams&quot;)<br>           traditionalNestedCalcButton.visibility = View.INVISIBLE<br>           val container = layoutInflater<br>               .inflate(R.layout.activity_nonnested_constraintlayout, null) as ViewGroup<br>           val measurementAsyncTask = MeasurementLayoutAsyncTask(<br>               getString(R.string.executing_nth_iteration),<br>               WeakReference(constraintNonNestedCalcButton),<br>               WeakReference(textViewFinish),<br>               WeakReference(container))<br>           measurementAsyncTask.execute()<br>       }<br>   }<br><br>   override fun onResume() {<br>       super.onResume()<br>       window.addOnFrameMetricsAvailableListener(frameMetricsListener, frameMetricsHandler)<br>   }<br><br>   override fun onPause() {<br>       super.onPause()<br>       window.removeOnFrameMetricsAvailableListener(frameMetricsListener)<br>   }<br><br>   /**<br>    * AsyncTask that triggers measure/layout in the background. Not to leak the Context of the<br>    * Views, take the View instances as WeakReferences.<br>    */<br>   private class MeasurementLayoutAsyncTask(val executingNthIteration: String,<br>                                            val startButtonRef: WeakReference&lt;Button&gt;,<br>                                            val finishTextViewRef: WeakReference&lt;TextView&gt;,<br>                                            val containerRef: WeakReference&lt;ViewGroup&gt;) : AsyncTask&lt;Void?, Int, Void?&gt;() {<br><br>       override fun doInBackground(vararg voids: Void?): Void? {<br>           for (i in 0 until TOTAL) {<br>               publishProgress(i)<br>               try {<br>                   Thread.sleep(100)<br>               } catch (ignore: InterruptedException) {<br>                   // No op<br>               }<br><br>           }<br>           return null<br>       }<br><br>       override fun onProgressUpdate(vararg values: Int?) {<br>           val startButton = startButtonRef.get() ?: return<br>           startButton.text = String.format(executingNthIteration, values[0], TOTAL)<br>           val container = containerRef.get() ?: return<br>           // Not to use the view cache in the View class, use the different measureSpecs<br>           // for each calculation. (Switching the<br>           // View.MeasureSpec.EXACT and View.MeasureSpec.AT_MOST alternately)<br>           measureAndLayoutExactLength(container)<br>           measureAndLayoutWrapLength(container)<br>       }<br><br>       override fun onPostExecute(aVoid: Void?) {<br>           val finishTextView = finishTextViewRef.get() ?: return<br>           finishTextView.visibility = View.VISIBLE<br>           val startButton = startButtonRef.get() ?: return<br>           startButton.visibility = View.GONE<br>       }<br><br>       private fun measureAndLayoutWrapLength(container: ViewGroup) {<br>           val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(<br>               WIDTH,<br>               View.MeasureSpec.AT_MOST)<br>           val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(<br>               HEIGHT,<br>               View.MeasureSpec.AT_MOST)<br>           container.measure(widthMeasureSpec, heightMeasureSpec)<br>           container.layout(0, 0, container.measuredWidth,<br>               container.measuredHeight)<br>       }<br><br>       private fun measureAndLayoutExactLength(container: ViewGroup) {<br>           val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(<br>               WIDTH,<br>               View.MeasureSpec.EXACTLY)<br>           val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(<br>               HEIGHT,<br>               View.MeasureSpec.EXACTLY)<br>           container.measure(widthMeasureSpec, heightMeasureSpec)<br>           container.layout(0, 0, container.measuredWidth,<br>               container.measuredHeight)<br>       }<br>   }<br><br>   companion object {<br><br>       private val TAG = &quot;MainActivity&quot;<br><br>       private val TOTAL = 100<br><br>       private val WIDTH = 1920<br><br>       private val HEIGHT = 1080<br>   }<br>}</pre><h4>1.2.2 activity_nested_view_hierarchy.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>   xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>   xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>   android:id=&quot;@+id/container&quot;<br>   android:layout_width=&quot;match_parent&quot;<br>   android:layout_height=&quot;match_parent&quot; &gt;<br><br>   &lt;Button<br>       android:id=&quot;@+id/button_start_calc_traditional&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:text=&quot;@string/start_calc_traditional&quot;<br>       app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>       app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>       app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>       app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>       android:layout_marginTop=&quot;16dp&quot; /&gt;<br><br>   &lt;Button<br>       android:id=&quot;@+id/textview_finish&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:layout_marginEnd=&quot;8dp&quot;<br>       android:layout_marginStart=&quot;8dp&quot;<br>       android:text=&quot;@string/finish&quot;<br>       android:visibility=&quot;gone&quot;<br>       app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>       app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>       app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>       app:layout_constraintRight_toRightOf=&quot;parent&quot; /&gt;<br><br>   &lt;Button<br>       android:id=&quot;@+id/button_start_calc_constraint&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:text=&quot;@string/start_calc_constraint&quot;<br>       app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>       app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>       app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>       app:layout_constraintVertical_bias=&quot;0&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>       app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>       android:layout_marginTop=&quot;8dp&quot;<br>       app:layout_constraintTop_toBottomOf=&quot;@+id/button_start_calc_traditional&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><h4>1.2.3 activity_nested_traditional.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br><br>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>   android:id=&quot;@+id/container&quot;<br>   android:layout_width=&quot;match_parent&quot;<br>   android:layout_height=&quot;match_parent&quot;&gt;<br><br>   &lt;ImageView<br>       android:src=&quot;@drawable/singapore&quot;<br>       android:layout_width=&quot;match_parent&quot;<br>       android:layout_height=&quot;150dp&quot;<br>       android:id=&quot;@+id/imageview_singapore&quot;<br>       android:scaleType=&quot;centerCrop&quot;<br>       android:contentDescription=&quot;@string/dummy&quot; /&gt;<br><br>   &lt;ImageView<br>       android:src=&quot;@drawable/ic_star&quot;<br>       android:layout_width=&quot;36dp&quot;<br>       android:layout_height=&quot;36dp&quot;<br>       android:id=&quot;@+id/favorite&quot;<br>       android:background=&quot;@drawable/info_background&quot;<br>       android:padding=&quot;5dp&quot;<br>       android:contentDescription=&quot;@string/dummy&quot;<br>       android:layout_below=&quot;@id/imageview_singapore&quot;<br>       android:layout_alignParentEnd=&quot;true&quot;<br>       android:layout_marginTop=&quot;-18dp&quot;<br>       android:layout_marginEnd=&quot;18dp&quot; /&gt;<br><br>   &lt;RelativeLayout<br>       android:layout_width=&quot;match_parent&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:layout_below=&quot;@id/imageview_singapore&quot; &gt;<br><br>       &lt;TextView<br>           android:text=&quot;@string/singapore&quot;<br>           android:layout_width=&quot;wrap_content&quot;<br>           android:layout_height=&quot;wrap_content&quot;<br>           android:id=&quot;@+id/title&quot;<br>           android:textSize=&quot;24sp&quot;<br>           android:layout_marginStart=&quot;16dp&quot;<br>           android:layout_marginTop=&quot;16dp&quot; /&gt;<br><br>       &lt;LinearLayout<br>           android:id=&quot;@+id/camera_area&quot;<br>           android:layout_width=&quot;match_parent&quot;<br>           android:layout_height=&quot;wrap_content&quot;<br>           android:orientation=&quot;horizontal&quot;<br>           android:layout_below=&quot;@id/title&quot; &gt;<br><br>           &lt;TextView<br>               android:text=&quot;@string/camera&quot;<br>               android:layout_width=&quot;wrap_content&quot;<br>               android:layout_height=&quot;wrap_content&quot;<br>               android:layout_gravity=&quot;center_vertical&quot;<br>               android:id=&quot;@+id/cameraLabel&quot;<br>               android:labelFor=&quot;@+id/cameraType&quot;<br>               android:layout_marginStart=&quot;16dp&quot; /&gt;<br><br>           &lt;RelativeLayout<br>               android:layout_width=&quot;match_parent&quot;<br>               android:layout_height=&quot;wrap_content&quot;&gt;<br><br>               &lt;EditText<br>                   android:id=&quot;@+id/cameraType&quot;<br>                   android:ems=&quot;10&quot;<br>                   android:inputType=&quot;textPersonName&quot;<br>                   android:text=&quot;@string/camera_value&quot;<br>                   android:layout_width=&quot;match_parent&quot;<br>                   android:layout_height=&quot;wrap_content&quot;<br>                   android:layout_centerVertical=&quot;true&quot;<br>                   android:layout_marginTop=&quot;8dp&quot;<br>                   android:layout_marginStart=&quot;8dp&quot;<br>                   android:layout_marginEnd=&quot;8dp&quot; /&gt;<br>           &lt;/RelativeLayout&gt;<br>       &lt;/LinearLayout&gt;<br><br>       &lt;LinearLayout<br>           android:id=&quot;@+id/setings_area&quot;<br>           android:layout_width=&quot;match_parent&quot;<br>           android:layout_height=&quot;wrap_content&quot;<br>           android:layout_below=&quot;@id/camera_area&quot;<br>           android:orientation=&quot;horizontal&quot;&gt;<br><br>           &lt;TextView<br>               android:text=&quot;@string/settings&quot;<br>               android:layout_width=&quot;wrap_content&quot;<br>               android:layout_height=&quot;wrap_content&quot;<br>               android:layout_gravity=&quot;center_vertical&quot;<br>               android:id=&quot;@+id/settingsLabel&quot;<br>               android:labelFor=&quot;@+id/settings&quot;<br>               android:layout_marginStart=&quot;16dp&quot; /&gt;<br><br>           &lt;RelativeLayout<br>               android:layout_width=&quot;match_parent&quot;<br>               android:layout_height=&quot;wrap_content&quot;&gt;<br><br>               &lt;EditText<br>                   android:layout_width=&quot;match_parent&quot;<br>                   android:layout_height=&quot;wrap_content&quot;<br>                   android:layout_centerVertical=&quot;true&quot;<br>                   android:inputType=&quot;textPersonName&quot;<br>                   android:text=&quot;@string/camera_settings&quot;<br>                   android:ems=&quot;10&quot;<br>                   android:id=&quot;@+id/settings&quot;<br>                   android:layout_marginStart=&quot;8dp&quot;<br>                   android:layout_marginEnd=&quot;8dp&quot;<br>                   android:layout_marginTop=&quot;8dp&quot; /&gt;<br>           &lt;/RelativeLayout&gt;<br>       &lt;/LinearLayout&gt;<br><br><br>       &lt;TextView<br>           android:text=&quot;@string/singapore_description&quot;<br>           android:layout_width=&quot;match_parent&quot;<br>           android:layout_height=&quot;wrap_content&quot;<br>           android:id=&quot;@+id/description&quot;<br>           android:fadingEdge=&quot;vertical&quot;<br>           android:ellipsize=&quot;end&quot;<br>           android:textSize=&quot;15sp&quot;<br>           android:layout_below=&quot;@id/setings_area&quot;<br>           android:layout_marginStart=&quot;16dp&quot;<br>           android:layout_marginTop=&quot;8dp&quot;<br>           android:layout_marginEnd=&quot;16dp&quot;<br>           android:layout_marginBottom=&quot;8dp&quot; /&gt;<br>   &lt;/RelativeLayout&gt;<br><br>   &lt;LinearLayout<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:layout_alignParentEnd=&quot;true&quot;<br>       android:layout_alignParentBottom=&quot;true&quot;&gt;<br><br>       &lt;Button<br>           android:text=&quot;@string/upload&quot;<br>           android:layout_width=&quot;wrap_content&quot;<br>           android:layout_height=&quot;wrap_content&quot;<br>           android:id=&quot;@+id/upload&quot;<br>           android:layout_marginEnd=&quot;16dp&quot;<br>           android:layout_marginBottom=&quot;16dp&quot; /&gt;<br><br>       &lt;Button<br>           android:text=&quot;@string/discard&quot;<br>           android:layout_width=&quot;wrap_content&quot;<br>           android:layout_height=&quot;wrap_content&quot;<br>           android:id=&quot;@+id/discard&quot;<br>           android:elevation=&quot;0dp&quot;<br>           android:layout_marginEnd=&quot;8dp&quot; /&gt;<br>   &lt;/LinearLayout&gt;<br>&lt;/RelativeLayout&gt;</pre><h4>1.2.4 activity_nonnested_constraintlayout.xml</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br><br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>   xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>   xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>   android:id=&quot;@+id/container&quot;<br>   android:layout_width=&quot;match_parent&quot;<br>   android:layout_height=&quot;match_parent&quot; &gt;<br><br>   &lt;ImageView<br>       android:src=&quot;@drawable/singapore&quot;<br>       android:layout_width=&quot;0dp&quot;<br>       android:layout_height=&quot;0dp&quot;<br>       android:id=&quot;@+id/header&quot;<br>       android:scaleType=&quot;centerCrop&quot;<br>       android:contentDescription=&quot;@string/dummy&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;@+id/container&quot;<br>       app:layout_constraintTop_toTopOf=&quot;@+id/container&quot;<br>       app:layout_constraintRight_toRightOf=&quot;@+id/container&quot;<br>       app:layout_constraintBottom_toBottomOf=&quot;@+id/favorite&quot;<br>       android:layout_marginBottom=&quot;16dp&quot;<br>       app:layout_constraintHorizontal_bias=&quot;1.0&quot;<br>       app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;<br><br>   &lt;ImageView<br>       android:src=&quot;@drawable/ic_star&quot;<br>       android:layout_width=&quot;36dp&quot;<br>       android:layout_height=&quot;36dp&quot;<br>       android:id=&quot;@+id/favorite&quot;<br>       android:background=&quot;@drawable/info_background&quot;<br>       android:padding=&quot;5dp&quot;<br>       android:contentDescription=&quot;@string/dummy&quot;<br>       app:layout_constraintTop_toTopOf=&quot;@+id/container&quot;<br>       app:layout_constraintRight_toRightOf=&quot;@+id/container&quot;<br>       android:layout_marginEnd=&quot;16dp&quot;<br>       app:layout_constraintBottom_toBottomOf=&quot;@+id/container&quot;<br>       android:layout_marginBottom=&quot;16dp&quot;<br>       app:layout_constraintVertical_bias=&quot;0.19&quot; /&gt;<br><br>   &lt;TextView<br>       android:text=&quot;@string/singapore&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:id=&quot;@+id/title&quot;<br>       android:textSize=&quot;24sp&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;@+id/container&quot;<br>       android:layout_marginStart=&quot;16dp&quot;<br>       app:layout_constraintTop_toBottomOf=&quot;@+id/header&quot;<br>       android:layout_marginTop=&quot;16dp&quot; /&gt;<br><br>   &lt;EditText<br>       android:layout_width=&quot;0dp&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:inputType=&quot;textPersonName&quot;<br>       android:text=&quot;@string/camera_value&quot;<br>       android:ems=&quot;10&quot;<br>       android:id=&quot;@+id/cameraType&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;@+id/settings&quot;<br>       app:layout_constraintTop_toBottomOf=&quot;@+id/title&quot;<br>       android:layout_marginTop=&quot;8dp&quot;<br>       app:layout_constraintRight_toRightOf=&quot;@+id/settings&quot; /&gt;<br><br>   &lt;TextView<br>       android:text=&quot;@string/camera&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:id=&quot;@+id/cameraLabel&quot;<br>       android:labelFor=&quot;@+id/cameraType&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;@+id/container&quot;<br>       android:layout_marginStart=&quot;16dp&quot;<br>       app:layout_constraintBaseline_toBaselineOf=&quot;@+id/cameraType&quot; /&gt;<br><br>   &lt;TextView<br>       android:text=&quot;@string/settings&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:id=&quot;@+id/settingsLabel&quot;<br>       android:labelFor=&quot;@+id/settings&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;@+id/container&quot;<br>       android:layout_marginStart=&quot;16dp&quot;<br>       app:layout_constraintBaseline_toBaselineOf=&quot;@+id/settings&quot; /&gt;<br><br>   &lt;EditText<br>       android:layout_width=&quot;0dp&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:inputType=&quot;textPersonName&quot;<br>       android:text=&quot;@string/camera_settings&quot;<br>       android:ems=&quot;10&quot;<br>       android:id=&quot;@+id/settings&quot;<br>       app:layout_constraintLeft_toRightOf=&quot;@+id/settingsLabel&quot;<br>       android:layout_marginStart=&quot;6dp&quot;<br>       app:layout_constraintTop_toBottomOf=&quot;@+id/cameraType&quot;<br>       android:layout_marginTop=&quot;8dp&quot;<br>       app:layout_constraintRight_toRightOf=&quot;@+id/description&quot; /&gt;<br><br>   &lt;Button<br>       android:text=&quot;@string/upload&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:id=&quot;@+id/upload&quot;<br>       app:layout_constraintRight_toRightOf=&quot;@+id/container&quot;<br>       android:layout_marginEnd=&quot;16dp&quot;<br>       app:layout_constraintBottom_toBottomOf=&quot;@+id/container&quot;<br>       android:layout_marginBottom=&quot;16dp&quot; /&gt;<br><br>   &lt;Button<br>       android:text=&quot;@string/discard&quot;<br>       android:layout_width=&quot;wrap_content&quot;<br>       android:layout_height=&quot;wrap_content&quot;<br>       android:id=&quot;@+id/discard&quot;<br>       android:elevation=&quot;0dp&quot;<br>       app:layout_constraintRight_toLeftOf=&quot;@+id/upload&quot;<br>       android:layout_marginEnd=&quot;8dp&quot;<br>       app:layout_constraintBaseline_toBaselineOf=&quot;@+id/upload&quot; /&gt;<br><br>   &lt;TextView<br>       android:text=&quot;@string/singapore_description&quot;<br>       android:layout_width=&quot;0dp&quot;<br>       android:layout_height=&quot;0dp&quot;<br>       android:id=&quot;@+id/description&quot;<br>       android:fadingEdge=&quot;vertical&quot;<br>       android:ellipsize=&quot;end&quot;<br>       android:textSize=&quot;15sp&quot;<br>       app:layout_constraintLeft_toLeftOf=&quot;@+id/container&quot;<br>       android:layout_marginStart=&quot;16dp&quot;<br>       app:layout_constraintTop_toBottomOf=&quot;@+id/settings&quot;<br>       android:layout_marginTop=&quot;8dp&quot;<br>       app:layout_constraintRight_toRightOf=&quot;@+id/container&quot;<br>       android:layout_marginEnd=&quot;16dp&quot;<br>       app:layout_constraintBottom_toTopOf=&quot;@+id/discard&quot;<br>       android:layout_marginBottom=&quot;8dp&quot; /&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><h3>1.3 Tool Test</h3><h4>1.3.1 LayoutInspector Tool Test</h4><p><strong>1.3.1.1 LayoutInspector Nested Layout Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uSHdmduY-yw3TUWm" /></figure><p><em>Figure 36. LayoutInspector result for nested layout hierarchy</em></p><p><strong>1.3.1.2 LayoutInspector Non Nested Layout Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b_OnL2pKE5-HAKXp" /></figure><p><em>Figure 37. LayoutInspector result for non nested layout hierarchy</em></p><p><strong>1.3.1.3 LayoutInspector Tool Test Result</strong></p><p>It is clearly visible from component tree of Figure 36 and Figure 37 that the layout hierarchy for non nested layout is less deeper than nested layout. This clearly indicates that Layout Inspector is effective in testing for nested layout hierarchies .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LTCePMmvx_YkaPcUeeOog.png" /></figure><h4>1.3.2 Debug GPU Overdraw Tool Test</h4><p><strong>1.3.2.1 Debug GPU Overdraw Nested Layout Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*pb_V1kqGFbbfAJ9z" /></figure><p><em>Figure 38. Debug GPU overdraw result for nested layout hierarchy</em></p><p><strong>1.3.2.2 Debug GPU Overdraw Non Nested Layout Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*x6IR5CsZbzrrLwG0" /></figure><p><em>Figure 39. Debug GPU overdraw result for non nested layout hierarchy</em></p><p><strong>1.3.2.3 Debug GPU Overdraw Tool Test Result</strong></p><p>It is clearly visible from the overdraw areas of nested layout hierarchy(Figure 38) and non nested layout hierarchy(Figure 39) that there is no difference in output given by Debug GPU overdraw developer option provided no extra overdrawing has been added deliberately while converting a nested layout to non nested layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNIxMqkF-LpklXKheEJy1A.png" /></figure><h4>1.3.3 Profile GPU rendering Tool Test</h4><p><strong>1.3.3.1 Profile GPU rendering Nested Layout Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*W4mte_--PXAzirwb" /></figure><p><em>Figure 40. Debug GPU overdraw result for nested layout hierarchy</em></p><p><strong>1.3.3.2 Profile GPU rendering Non Nested Layout Test</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*KBlUWzbOTTc9fXxf" /></figure><p><em>Figure 41. Profile GPU rendering result for non nested layout hierarchy</em></p><p><strong>1.3.2.3 Profile GPU rendering Tool Test Result</strong></p><p>It is clearly visible from the rendering bars for nested layout hierarchy(Figure 40) and non nested layout hierarchy(Figure 41) that the rendering bars for non nested layout hierarchy are smaller in height than rendering bars for nested layout hierarchy. This indicates that the profile GPU rendering is effective in detecting the rendering performance issues caused by nested view hierarchy but by just looking at the bar heights, a person can not attribute that the increased bar height is caused by just nested layout hierarchy .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZn-FCvapE5WJjVoz0_26A.png" /></figure><h4>1.3.4 Show View Updates Tool Test</h4><p><strong>1.3.4.1 Show View Updates Nested Layout Test</strong></p><p>The result of applying Show View Updates developer option on nested layout is shown in <a href="https://doi.org/10.5281/zenodo.7008949">Reference</a></p><p><strong>1.3.4.2 Show View Updates Non Nested Layout Test</strong></p><p>The result of applying Show View Updates developer option on non nested layout is shown in <a href="https://doi.org/10.5281/zenodo.7008959">Reference</a></p><p><strong>1.3.4.3 Show View Updates Tool Test Result</strong></p><p>It is clearly visible from the video result for nested layout hierarchy<a href="https://doi.org/10.5281/zenodo.7008949">[16] </a>and non nested layout hierarchy[<a href="https://doi.org/10.5281/zenodo.7008959">17]</a> that there is no significant difference in results of applying this tool to both types of layouts. This indicates that the Show view updates tool is ineffective in detecting the rendering performance issues caused by nested view hierarchy .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-qps6dVZca62xMxbdKxAg.png" /></figure><h4>1.3.5 Android CPU Profiler Tool Test</h4><p><strong>1.3.5.1 Android CPU Profiler Nested Layout Test</strong><br><strong>1.3.5.1.1 Android CPU Profiler Nested Layout Test — System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*_ynjPQxV3PGh0R8T" /></figure><p><em>Figure 42. The CPU profiler system trace visualization for nested layout. This window clearly shows two jank frames.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*kAQBJD7adKGzEWJs" /></figure><p><em>Figure 43. The CPU profiler system trace — All Frame visualization for nested layout. This window shows all frames created in the current system trace recording.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*wIBjzMCRFS_vaqCN" /></figure><p><em>Figure 44. The CPU profiler system trace — Janky Frame visualization for nested layout. This window shows all janky frames created in the current system trace recording</em></p><p>From Figure 42, we see that the traversal bar coincides with the primary jank bar corresponding to Frame 7273315. So, in order to investigate further, we open details for traversal window by clicking on the traversal bar. The results are shown in Figure 45,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/0*XcqqYGfbzUUshs4R" /></figure><p><em>Figure 45. The CPU profiler system trace — traversal event visualization for nested layout. This window shows summary of details for the traversal event.</em></p><p>From the selected event above, it can be seen that the traversal event takes 41.35 ms which is much higher than the frame duration of 16.6 ms. In order to get further details into what is causing this extended time in traversal phase, we further explore the top Down view of the traversal event, which shows that measure phase itself is the biggest time consuming task in traversal phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*IBXEr7FdMNh9brC_" /></figure><p><em>Figure 46. The CPU profiler system trace — traversal event Top Down visualization for nested layout. This window shows summary of what different calls are made in the traversal phase.</em></p><p>It can be found from the Figure 46, that not much information is provided regarding what exactly within the measure call is causing the extended time. This gives an indication into further exploring the Nested layout performance issue using Java/kotlin method tracing further to check the root cause of extended measure time.</p><p><strong>1.3.5.1.2 Android CPU Profiler Nested Layout Test — Java/Kotlin Method Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*IwPX4e0S7NMlnexh" /></figure><p><em>Figure 47. The CPU profiler kotlin/java method trace visualization for nested layout. This window clearly shows that measure calls in traversal phase are the biggest contributors in extended cpu time . Additionally, within measure calls, LinearLayout measure call is the sole contributors.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*Y9LGcZoLfoZGIuuX" /></figure><p><em>Figure 48. The CPU profiler kotlin/java method trace Top Down visualization for nested layout. This window clearly shows that measure calls in traversal phase are the biggest contributors in extended cpu time . Additionally, within measure calls, LinearLayout measure call is the sole contributors.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*ijh1Zab_lgvzG6k2" /></figure><p><em>Figure 49. The CPU profiler kotlin/java method trace Flame chart visualization for nested layout. This window clearly shows that measure calls in Linear Layout the biggest contributors in extended cpu time within Relative layout(root layout) measure calls.</em></p><p>Above profiler results for system trace and java/kotlin method trace clearly demonstrate that nested layouts are the main culprits for extended frame timings which in turn leads to heavier janky frame. In the next section, we will run the same steps on non nested layout created using constraint layout to see if it is more performant than our nested layout provided the visual appearance of the layout remains the same.</p><p><strong>1.3.5.2 Android CPU Profiler Non Nested Layout Test4.1.3.5.2.1 Android CPU Profiler Nested Layout Test — System Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z6ak9EkI6rXZC3ZO" /></figure><p><em>Figure 50. The CPU profiler system trace visualization for non nested layout. This window clearly shows one frame with frame duration of 20.21 ms which is slightly above ideal 16.6 ms..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X3VKnw0ZVEY_7rD7" /></figure><p><em>Figure 51. The CPU profiler system trace — All Frame visualization for non nested layout. This window shows all frames created in the current system trace recording.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pi431XI3vBku6jnF" /></figure><p><em>Figure 52. The CPU profiler system trace — Janky Frame visualization for non nested layout. This window shows all janky frames created in the current system trace recording</em></p><p>From Figure 50, we see that the traversal bar coincides with the primary jank bar corresponding to Frame 594483. So, in order to investigate further, we open details for traversal window by clicking on the traversal bar. The results are shown in Figure 43,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vuMJSBZKYkkWyMX4" /></figure><p><em>Figure 53. The CPU profiler system trace — traversal event visualization for non nested layout. This window shows summary of details for the traversal event.</em></p><p>From the selected event above, it can be seen that the traversal event takes just 19.42 ms in comparison to 41.35 ms for nested layout which is much higher than the frame duration of 16.6 ms. In order to get further details into what is causing this extended time in traversal phase, we further explore the Top Down view of the traversal event, which shows that measure phase itself is the biggest time consuming task in traversal phase.</p><p><em>Figure 54. The CPU profiler system trace — traversal event Top Down visualization for nested layout. This window shows summary of what different calls are made in the traversal phase.</em></p><p>It can be found from the Figure 54, that not much information is provided regarding what exactly within the measure call is causing the extended time. This gives an indication into further exploring the Nested layout performance issue using Java/kotlin method tracing further to check the root cause of extended measure time.</p><p><strong>1.3.5.2.2 Android CPU Profiler Nested Layout Test — Java/Kotlin Method Trace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6LUbG9bft2E9kU5J" /></figure><p><em>Figure 55. The CPU profiler kotlin/java method trace visualization for nested layout. This window clearly shows that measure calls in traversal phase are shorter than measure calls as shown in Figure 37.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5PyU5mBjFQK43z0b" /></figure><p><em>Figure 56. The CPU profiler kotlin/java method trace Top Down visualization for nested layout. This window clearly shows that measure calls in traversal phase take just around 6 ms in comparison 101 ms for nested layout.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YFM24p3koyjnVCoe" /></figure><p><em>Figure 57. The CPU profiler kotlin/java method trace Flame chart visualization for nested layout. This window clearly shows that measure calls are quite smaller in comparison for nested layout shown in Fig 37.</em></p><p>Above profiler results for system trace and java/kotlin method trace clearly demonstrate that nested layouts are the main culprits for extended frame timings which in turn leads to heavier janky frame and usage of a non nested approach such as contraint layout leads to a big reduction in jank frame reduction .</p><p><strong>1.3.5.3 Android CPU Profiler Tool Test Result</strong></p><p>It is clearly visible from the CPU profiler result for nested layout hierarchy and non nested layout hierarchy that there is significant reduction in number of jank frames and the duration of frames itself by using non nested layout hierarchy in comparison to nested layout hierarchy.. This indicates that the CPU profiler tool is effective in detecting the rendering performance issues caused by nested view hierarchy .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kErkQyEE0TnSbp333cMTtQ.png" /></figure><p>This clearly shows that there is 50 percent improvement in number of jank frames by using constraintlayout in comparison to nested linear-relative layout. Moreover, there is 43 percent improvement in frame duration for constraint layout in comparison to nested linear-relative layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-qtYBOdVBMVmUZeDNjpnA.png" /></figure><h4>1.3.6 Tool Test Results on Nested View Hierarchy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rfSc3eDrLb6m_mn4ksPaQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45493f49c33c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Dagger Scoping works?]]></title>
            <link>https://er-abhishek-luthra.medium.com/how-dagger-scoping-works-6c1d207e46c5?source=rss-8e808d26f4c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c1d207e46c5</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abhishek Luthra]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 14:51:57 GMT</pubDate>
            <atom:updated>2020-11-13T15:03:35.727Z</atom:updated>
            <content:encoded><![CDATA[<p>When I learned how to use Dagger, the concept of so-called scopes was one of the most difficult to grasp.</p><p>Today I realize that the best way to understand Dagger scopes is to dive into the depths of the generated code. It sounds complicated, but I assure you that it is not. Well, it is a little complicated if you do it on your own, but you don’t have to.</p><p>In this post, I will take you through the code that Dagger generates and explain the inner workings of scopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*ymO6NrhliEbKXY1Zk0ExIw.png" /></figure><h3>Dagger 2 dependency injection framework:</h3><p>I would like to make sure that the terminology I’m going to use is clear, so let’s briefly review Dagger’s constructs. If you’re completely new to Dagger, you might want to start with a proper Dagger tutorial and get back to this post afterward.</p><p>Dagger 2 is a dependency injection framework for Android and Java. Originally created by Square, it is now being maintained by Google.</p><p>The basic “building blocks” that Dagger 2 uses are as follows:</p><ul><li>Components. Components are “injectors” that perform actual injection into “clients”.</li><li>Modules. Modules are the objects in which “object graph” structure is defined (the way “services” need to be instantiated).</li><li>Scopes. Scopes are Java annotations which, when used, change the way “services” are being instantiated upon injection.</li></ul><p>Please note the terminology: in this post, whenever I say “service” I’m not referring to the android Service class, but to some object which is being injected into another object; whenever I say “client” I’m referring to some object that is being injected with another object.</p><h3>Injection without scopes:</h3><p>To better understand what scopes do, let’s review what happens when I inject “un-scoped services”.</p><p>For simplicity, I’m going to inject this class:</p><pre><strong>public class </strong>UnScopedService {<br>    <strong>public </strong>UnScopedService() {<br>    }<br>}</pre><p>UnScopedService is being declared as a service (i.e. being declared as “injectable”) in this module:</p><pre>@Module<br>public class DemoModule {@Provides<br> public UnScopedService provideUnscopedService() {<br>  return new UnScopedService();<br> }}</pre><p>This is the component that makes use of DemoModule and declares MainActivity as a client (i.e. declares that it can inject services into MainActivity):</p><pre>@Component(modules = {DemoModule.<strong>class</strong>})<br><strong>public interface </strong>DemoComponent {</pre><pre>    <strong>void </strong>inject(MainActivity mainActivity);<br>}</pre><p>And the client is also very simple (the contents of activity_main.xml are irrelevant to our current discussion):</p><pre><strong>public class </strong>MainActivity <strong>extends </strong>AppCompatActivity {<br> <br>    @Inject<br>    UnScopedService <strong>mUnScopedService</strong>;<br>    <strong>private </strong>DemoComponent <strong>mDemoComponent</strong>;</pre><pre>    @Override<br>    <strong>public void </strong>onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {<br>        getDemoComponent().inject(<strong>this</strong>);<br>        <strong>super</strong>.onCreate(savedInstanceState, persistentState);<br>        setContentView(R.layout.<strong><em>activity_main</em></strong>);<br>    }</pre><pre>    <strong>private </strong>DemoComponent getDemoComponent() {<br>        <strong>if </strong>(<strong>mDemoComponent </strong>== <strong>null</strong>) {<br>            <strong>mDemoComponent </strong>= DaggerDemoComponent.<em>builder</em>().demoModule(<strong>new </strong>DemoModule()).build();<br>        }<br>        <strong>return mDemoComponent</strong>;<br>    }</pre><pre>}</pre><p>After building this project I can take a look at the actual code which performs the injection.</p><p>Starting with the inject(MainActivity) method of DemoComponent, I trace the usages and implementations of a series of classes and eventually reach MainActivity_MembersInjector class:</p><pre><strong>public final class </strong>MainActivity_MembersInjector <strong>implements </strong>MembersInjector&lt;MainActivity&gt; {</pre><pre>    <strong>private final </strong>Provider&lt;UnScopedService&gt; <strong>mUnScopedServiceProvider</strong>;</pre><pre>    <strong>public </strong>MainActivity_MembersInjector(Provider&lt;UnScopedService&gt; mUnScopedServiceProvider) {<br>        <strong>assert </strong>mUnScopedServiceProvider != <strong>null</strong>;<br>        <strong>this</strong>.<strong>mUnScopedServiceProvider </strong>= mUnScopedServiceProvider;<br>    }</pre><pre>    <strong>public static </strong>MembersInjector&lt;MainActivity&gt; create(<br>            Provider&lt;UnScopedService&gt; mUnScopedServiceProvider) {<br>        <strong>return new </strong>MainActivity_MembersInjector(mUnScopedServiceProvider);<br>    }</pre><pre>    @Override<br>    <strong>public void </strong>injectMembers(MainActivity instance) {<br>        <strong>if </strong>(instance == <strong>null</strong>) {<br>            <strong>throw new </strong>NullPointerException(<strong>&quot;Cannot inject members into a null reference&quot;</strong>);<br>        }<br>        instance.<strong>mUnScopedService </strong>= <strong>mUnScopedServiceProvider</strong>.get();<br>    }</pre><pre>    <strong>public static void </strong>injectMUnScopedService(<br>            MainActivity instance, Provider&lt;UnScopedService&gt; mUnScopedServiceProvider) {<br>        instance.<strong>mUnScopedService </strong>= mUnScopedServiceProvider.get();<br>    }<br>}</pre><p>The last Line in injectMembers method is where the actual injection of UnScopedService takes place. Note that the service is not constructed here, but is retrieved from an instance of Provider interface.</p><p>To find out which implementation of Provider was used, I search for usages of MainActivity_MembersInjector#create() method. It is being called from DaggerDemoComponent:</p><pre><strong>public final class </strong>DaggerDemoComponent <strong>implements </strong>DemoComponent {<br>    <strong>private </strong>Provider&lt;UnScopedService&gt; <strong>provideUnscopedServiceProvider</strong>;</pre><pre>    <strong>private </strong>MembersInjector&lt;MainActivity&gt; <strong>mainActivityMembersInjector</strong>;</pre><pre>    <strong>private </strong>DaggerDemoComponent(Builder builder) {<br>        <strong>assert </strong>builder != <strong>null</strong>;<br>        initialize(builder);<br>    }</pre><pre>    <strong>public static </strong>Builder builder() {<br>        <strong>return new </strong>Builder();<br>    }</pre><pre>    <strong>public static </strong>DemoComponent create() {<br>        <strong>return new </strong>Builder().build();<br>    }</pre><pre>    @SuppressWarnings(<strong>&quot;unchecked&quot;</strong>)<br>    <strong>private void </strong>initialize(<strong>final </strong>Builder builder) {</pre><pre>        <strong>this</strong>.<strong>provideUnscopedServiceProvider </strong>=<br>                DemoModule_ProvideUnscopedServiceFactory.<em>create</em>(builder.<strong>demoModule</strong>);</pre><pre>        <strong>this</strong>.<strong>mainActivityMembersInjector </strong>=<br>                MainActivity_MembersInjector.<em>create</em>(<strong>provideUnscopedServiceProvider</strong>);<br>    }</pre><pre>    @Override<br>    <strong>public void </strong>inject(MainActivity mainActivity) {<br>        <strong>mainActivityMembersInjector</strong>.injectMembers(mainActivity);<br>    }</pre><pre>    <strong>public static final class </strong>Builder {<br>        <strong>private </strong>DemoModule <strong>demoModule</strong>;</pre><pre>        <strong>private </strong>Builder() {}</pre><pre>        <strong>public </strong>DemoComponent build() {<br>            <strong>if </strong>(<strong>demoModule </strong>== <strong>null</strong>) {<br>                <strong>this</strong>.<strong>demoModule </strong>= <strong>new </strong>DemoModule();<br>            }<br>            <strong>return new </strong>DaggerDemoComponent(<strong>this</strong>);<br>        }</pre><pre>        <strong>public </strong>Builder demoModule(DemoModule demoModule) {<br>            <strong>this</strong>.<strong>demoModule </strong>= Preconditions.checkNotNull(demoModule);<br>            <strong>return this</strong>;<br>        }<br>    }<br>}</pre><p>As you can see in the initialize method, DemoModule_ProvideUnscopedServiceFactory is being used as a Provider for instances of UnScopedService.</p><p>Let’s see what’s going on inside this class:</p><pre><strong>public final class </strong>DemoModule_ProvideUnscopedServiceFactory <strong>implements </strong>Factory&lt;UnScopedService&gt; {<br>    <strong>private final </strong>DemoModule <strong>module</strong>;</pre><pre>    <strong>public </strong>DemoModule_ProvideUnscopedServiceFactory(DemoModule module) {<br>        <strong>assert </strong>module != <strong>null</strong>;<br>        <strong>this</strong>.<strong>module </strong>= module;<br>    }</pre><pre>    @Override<br>    <strong>public </strong>UnScopedService get() {<br>        <strong>return </strong>Preconditions.checkNotNull(<br>                <strong>module</strong>.provideUnscopedService(),<br>                <strong>&quot;Cannot return null from a non-@Nullable @Provides method&quot;</strong>);<br>    }</pre><pre>    <strong>public static </strong>Factory&lt;UnScopedService&gt; create(DemoModule module) {<br>        <strong>return new </strong>DemoModule_ProvideUnscopedServiceFactory(module);<br>    }<br>}</pre><p>The code in the last line in getting method simply obtains an instance of UnScopedService from DemoModule, which is the class that I myself defined. Looks like when a non-scoped service needs to be injected, the code that Dagger 2 generates simply delegates the instantiation of that service to a method in the user-defined Module class.</p><p>Imagine that I would like to use the same instance of DemoComponent to inject UnScopedService into multiple fields. Since each injection into a field results in a new instance being retrieved from the module, each field will point to a different service.</p><p>Remember this point because, as we’ll see shortly, it is exactly this mechanism of instantiation of a new service for each field that scopes will affect.</p><h3>Injection with @Singleton scope:</h3><p>Dagger 2 recognizes a single predefined scope: @Singleton. Let me show you how to apply scope to service.</p><p>Then I’ll dig into what happens when Dagger injects service annotated with @Singleton scope.</p><p>The scoped service will also be very simple:</p><pre><strong>public class </strong>SingletonScopedService {</pre><pre>    <strong>public </strong>SingletonScopedService() {<br>    }<br>    <br>}</pre><p>Please note that the service itself has no dependencies on the Dagger 2 framework, and, therefore, is not aware of its scope. I include the scope’s name in the service’s name just for a purpose of this tutorial, but you should not do the same in your projects.</p><p>In order to assign a scope to the service, we add @Singleton annotation to its provider method in DemoModule class:</p><pre>@Module<br><strong>public class </strong>DemoModule {<br>    @Provides<br>    <strong>public </strong>UnScopedService provideUnscopedService() {<br>        <strong>return new </strong>UnScopedService();<br>    }</pre><pre>    @Provides<br>    @Singleton<br>    <strong>public </strong>SingletonScopedService singletonScopedService() {<br>        <strong>return new </strong>SingletonScopedService();<br>    }<br>}</pre><p>Dagger 2 enforces a rule that in order to inject scoped services, the injecting component should also be annotated with the corresponding scope:</p><pre>@Singleton<br>@Component(modules = {DemoModule.<strong>class</strong>})<br><strong>public interface </strong>DemoComponent {</pre><pre>    <strong>void </strong>inject(MainActivity mainActivity);<br>}</pre><p>And the client that uses both services becomes:</p><pre><strong>public class </strong>MainActivity <strong>extends </strong>AppCompatActivity {</pre><pre>    @Inject<br>    UnScopedService <strong>mUnScopedService</strong>;</pre><pre>    @Inject<br>    SingletonScopedService <strong>mSingletonScopedService</strong>;</pre><pre>    <strong>private </strong>DemoComponent <strong>mDemoComponent</strong>;</pre><pre>    @Override<br>    <strong>public void </strong>onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {<br>        getDemoComponent().inject(<strong>this</strong>);<br>        <strong>super</strong>.onCreate(savedInstanceState, persistentState);<br>        setContentView(R.layout.<strong><em>activity_main</em></strong>);<br>    }</pre><pre>    <strong>private </strong>DemoComponent getDemoComponent() {<br>        <strong>if </strong>(<strong>mDemoComponent </strong>== <strong>null</strong>) {<br>            <strong>mDemoComponent </strong>= DaggerDemoComponent.<em>builder</em>().demoModule(<strong>new </strong>DemoModule()).build();<br>        }<br>        <strong>return mDemoComponent</strong>;<br>    }<br>}</pre><p>Now it is time to trace the methods and classes involved in the injection of SingletonScopedService in exactly the same manner as I did for UnScopedService beforehand.</p><p>When I do this I find out that the only difference in treatment of these services is in DaggerDemoComponent class:</p><pre><strong>public final class </strong>DaggerDemoComponent <strong>implements </strong>DemoComponent {<br>    <strong>private </strong>Provider&lt;UnScopedService&gt; <strong>provideUnscopedServiceProvider</strong>;</pre><pre>    <strong>private </strong>Provider&lt;SingletonScopedService&gt; <strong>singletonScopedServiceProvider</strong>;</pre><pre>    <strong>private </strong>MembersInjector&lt;MainActivity&gt; <strong>mainActivityMembersInjector</strong>;</pre><pre>    <strong>private </strong>DaggerDemoComponent(Builder builder) {<br>        <strong>assert </strong>builder != <strong>null</strong>;<br>        initialize(builder);<br>    }</pre><pre>    <strong>public static </strong>Builder builder() {<br>        <strong>return new </strong>Builder();<br>    }</pre><pre>    <strong>public static </strong>DemoComponent create() {<br>        <strong>return new </strong>Builder().build();<br>    }</pre><pre>    @SuppressWarnings(<strong>&quot;unchecked&quot;</strong>)<br>    <strong>private void </strong>initialize(<strong>final </strong>Builder builder) {</pre><pre>        <strong>this</strong>.<strong>provideUnscopedServiceProvider </strong>=<br>                DemoModule_ProvideUnscopedServiceFactory.<em>create</em>(builder.<strong>demoModule</strong>);</pre><pre>        <strong>this</strong>.<strong>singletonScopedServiceProvider </strong>=<br>                DoubleCheck.<em>provider</em>(DemoModule_SingletonScopedServiceFactory.create(builder.<strong>demoModule</strong>));</pre><pre>        <strong>this</strong>.<strong>mainActivityMembersInjector </strong>=<br>                MainActivity_MembersInjector.<em>create</em>(<br>                        <strong>provideUnscopedServiceProvider</strong>, <strong>singletonScopedServiceProvider</strong>);<br>    }</pre><pre>    @Override<br>    <strong>public void </strong>inject(MainActivity mainActivity) {<br>        <strong>mainActivityMembersInjector</strong>.injectMembers(mainActivity);<br>    }</pre><pre>    <strong>public static final class </strong>Builder {<br>        <strong>private </strong>DemoModule <strong>demoModule</strong>;</pre><pre>        <strong>private </strong>Builder() {}</pre><pre>        <strong>public </strong>DemoComponent build() {<br>            <strong>if </strong>(<strong>demoModule </strong>== <strong>null</strong>) {<br>                <strong>this</strong>.<strong>demoModule </strong>= <strong>new </strong>DemoModule();<br>            }<br>            <strong>return new </strong>DaggerDemoComponent(<strong>this</strong>);<br>        }</pre><pre>        <strong>public </strong>Builder demoModule(DemoModule demoModule) {<br>            <strong>this</strong>.<strong>demoModule </strong>= Preconditions.checkNotNull(demoModule);<br>            <strong>return this</strong>;<br>        }<br>    }<br>}</pre><p>Take a close look at the code in the initialize method. While DemoModule_ProvideUnscopedServiceFactory is directly used in MainActivity_MembersInjector, DemoModule_SingletonScopedServiceFactory is wrapped by DoubleCheck(which is another implementation of Provider interface).</p><p>Since this is the only difference between injection mechanisms of UnScopedService and SignletonScopedService by Dagger, then whatever functional differences @Singleton scope introduces, all of them will be due to Decoration by DoubleCheck class.</p><pre><strong>public final class </strong>DoubleCheck&lt;T&gt; <strong>implements </strong>Provider&lt;T&gt;, Lazy&lt;T&gt; {<br>    <strong>private static final </strong>Object <strong><em>UNINITIALIZED </em></strong>= <strong>new </strong>Object();</pre><pre>    <strong>private volatile </strong>Provider&lt;T&gt; <strong>provider</strong>;<br>    <strong>private volatile </strong>Object <strong>instance </strong>= <strong><em>UNINITIALIZED</em></strong>;</pre><pre>    <strong>private </strong>DoubleCheck(Provider&lt;T&gt; provider) {<br>        <strong>assert </strong>provider != <strong>null</strong>;<br>        <strong>this</strong>.<strong>provider </strong>= provider;<br>    }</pre><pre>    @SuppressWarnings(<strong>&quot;unchecked&quot;</strong>) <em>// cast only happens when result comes from the provider<br>    </em>@Override<br>    <strong>public </strong>T get() {<br>        Object result = <strong>instance</strong>;<br>        <strong>if </strong>(result == <strong><em>UNINITIALIZED</em></strong>) {<br>            <strong>synchronized </strong>(<strong>this</strong>) {<br>                result = <strong>instance</strong>;<br>                <strong>if </strong>(result == <strong><em>UNINITIALIZED</em></strong>) {<br>                    result = <strong>provider</strong>.get();<br>                    Object currentInstance = <strong>instance</strong>;<br>                    <strong>if </strong>(currentInstance != <strong><em>UNINITIALIZED </em></strong>&amp;&amp; currentInstance != result) {<br>                        <strong>throw new </strong>IllegalStateException(<strong>&quot;Scoped provider was invoked recursively returning &quot;<br>                                </strong>+ <strong>&quot;different results: &quot; </strong>+ currentInstance + <strong>&quot; &amp; &quot; </strong>+ result + <strong>&quot;. This is likely &quot;<br>                                </strong>+ <strong>&quot;due to a circular dependency.&quot;</strong>);<br>                    }<br>                    <strong>instance </strong>= result;<br>                    <strong>provider </strong>= <strong>null</strong>;<br>                }<br>            }<br>        }<br>        <strong>return </strong>(T) result;<br>    }</pre><pre>    <strong>public static </strong>&lt;T&gt; Provider&lt;T&gt; provider(Provider&lt;T&gt; delegate) {<br>        checkNotNull(delegate);<br>        <strong>if </strong>(delegate <strong>instanceof </strong>DoubleCheck) {<br>            <strong>return </strong>delegate;<br>        }<br>        <strong>return new </strong>DoubleCheck&lt;T&gt;(delegate);<br>    }</pre><pre>    <strong>public static </strong>&lt;T&gt; Lazy&lt;T&gt; lazy(Provider&lt;T&gt; provider) {<br>        <strong>if </strong>(provider <strong>instanceof </strong>Lazy) {<br>            @SuppressWarnings(<strong>&quot;unchecked&quot;</strong>) <strong>final </strong>Lazy&lt;T&gt; lazy = (Lazy&lt;T&gt;) provider;<br>            <strong>return </strong>lazy;<br>        }<br>        <strong>return new </strong>DoubleCheck&lt;T&gt;(checkNotNull(provider));<br>    }<br>}</pre><p>Even though this code looks complicated, it is the standard approach to ensuring that only one instance of service will be returned. This class caches the service returned by the first call to get() method, and then returns the same service on subsequent calls.</p><p>This makes DoubleCheck a Caching Decorator — it is a provider that wraps around another provider and caches the instance returned by it.</p><p>It is worth noting that the implementation of get() method in DoubleCheck makes use of a thread-safe “double check” idiom. This might be important if you intend to use DemoComponent from multiple threads. However, in practice, I have never seen a reason to perform injection on a non-UI thread in Android.</p><p>What would happen if I’d use the same instance of DemoComponent to inject SingletonScopedService into multiple fields?</p><p>Well, since the first injected service is being cached, all fields would end up having a reference to the same object.</p><p>This outcome is different from what would happen with fields of type UnScopedService (each of which would point to a different service) and this is the only difference introduced by @Singleton scope annotation.</p><p><strong>Injection with user-defined scope:</strong></p><p>In addition to a predefined @Singleton scope, I can define my own scopes in the following manner (this code should be in a file named CustomScope.java):</p><pre>@Scope<br>@Retention(RetentionPolicy.<strong><em>RUNTIME</em></strong>)<br><strong>public </strong>@<strong>interface </strong>CustomScope {<br>}</pre><p>Once the scope is defined in this manner, I can use it in my project. For example, I could replace all occurrences of @Singleton annotation with @CustomScope annotation.</p><p>If I trace the auto-generated code just like before, I’ll find out that Dagger treats @CustomScope in exactly the same way as it treats @Singleton scope. This means that “all scopes built equal” and the names of the scopes are irrelevant from Dagger’s perspective (though I do encourage you to name them descriptively for readability).</p><h3>Conclusion:</h3><ul><li>Any time an un-scoped service is being injected by the same component, a new instance of a service is created.</li><li>The first time a @Singleton scoped service is being injected, it is instantiated and cached inside the injecting component, and then the same exact instance will be used upon injection into other fields of the same type by the same component.</li><li>Custom user-defined scopes are functionally equivalent to a predefined @Singleton Scope</li><li>Injection of scoped services is thread-safe.</li></ul><p>That’s what scopes actually do.</p><p>Since components cache and reuse the same instance of scoped services upon injection (irrespective of scope’s name), the question of “whether the injected service is singleton or not” can be reduced to a question of “whether instances of a service were injected with the same component”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c1d207e46c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>