<?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 Andrey Bogomolov on Medium]]></title>
        <description><![CDATA[Stories by Andrey Bogomolov on Medium]]></description>
        <link>https://medium.com/@tipapro?source=rss-d9d9fd536586------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Andrey Bogomolov on Medium</title>
            <link>https://medium.com/@tipapro?source=rss-d9d9fd536586------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:31:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tipapro/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[Conscious Compose optimization 2: Tackling composition]]></title>
            <link>https://proandroiddev.com/conscious-compose-optimization-2-tackling-composition-f3e42ce3069d?source=rss-d9d9fd536586------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3e42ce3069d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Andrey Bogomolov]]></dc:creator>
            <pubDate>Thu, 02 May 2024 15:09:07 GMT</pubDate>
            <atom:updated>2024-05-02T15:09:07.793Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p01HtK3J5QTwqM06lWfNYQ.png" /><figcaption>Image generated by Kandinsky</figcaption></figure><p>Jetpack Compose is constantly evolving, opening new horizons for developers to optimize. Since our last review, we have made significant progress, reducing scrolling lag from 5–7% to zero. In this article, we will share fresh discoveries and advanced practices in optimizing Compose. For a deeper dive into the topic, we recommend reading the first part.</p><p>Article series:</p><p>1. <a href="https://proandroiddev.com/conscious-compose-optimization-e16144b80eef">Conscious Compose optimization</a> (<a href="https://habr.com/p/742854/">original</a>)<br>2. Conscious Compose optimization 2: Tackling composition (current) (<a href="https://habr.com/p/796437/">original</a>)</p><p><strong>Table of contents</strong></p><ul><li><a href="#">Introduction</a></li><li><a href="#afcd">Composition — a dethroned god</a><br>– <a href="#771f">The initial composition problem</a><br>– <a href="#22b1">Modifier.Node</a><br>– <a href="#7498">Problems with DerivedState and remember</a><br>– <a href="#06fb">Balancing Compose with traditional Kotlin techniques</a><br>– <a href="#42bb">Pre-rendering</a><br>– <a href="#f400">Deferred Composition</a></li><li><a href="#0b89">Painter</a><br>– <a href="#8575">Xml icons vs Compose icons</a><br>– <a href="#f406">Painter instability</a><br>– <a href="#1071">Extracting the Painter</a></li><li><a href="#290a">Design system</a><br>– <a href="#2bc1">Color scheme</a><br>– <a href="#7c25">Mistakes of the Past</a></li><li><a href="#49c1">Formatters</a></li><li><a href="#5dbb">Micro-optimizations</a><br>– <a href="#d73e">Autoboxing</a><br>– <a href="#cb89">Fast methods</a><br>– <a href="#bcbb">Effective structures</a><br>– <a href="#03c6">Nested “if” statements</a></li><li><a href="#762f">Innovations</a><br>– <a href="#5542">Specifying the stability of external types</a><br>– <a href="#f2ce">Strong skipping mode</a></li><li><a href="#814b">Toolkit</a><br>– <a href="#242f">Viewing Compose source code</a><br>– <a href="#05c9">Vkompose plugin</a><br>– <a href="#770d">Detekt</a></li><li><a href="#fbe4">Summary</a></li></ul><h3>Composition — a dethroned god</h3><h4>The initial composition problem</h4><p>In the first part, one of the issues with lazy lists was described — using SubcomposeLayout under the hood. According to developers, another problem is the speed of initial composition. During this costly step, the element tree is constructed for the first time. For lazy lists, this moment is especially critical, as the initial composition occurs with the creation of each element.</p><p>In the <a href="https://youtu.be/h-b3-DWYhjo?t=2025">podcast</a>, developers emphasize that Compose was designed with the notion that it is easier for people to think in terms of simple layouts (Box, Column, Row), rather than complex ones like ConstraintLayout. Unlike View, Compose does not face the issue of exponentially increasing dimensions, as they are limited to a single pass. Function skips also help solve the nesting issue. However, this is not the case with initial composition, which requires processing thousands of layouts. Developers aim to reduce this burden: upgrading from Compose 1.4 to 1.6 will increase list performance <a href="https://www.droidcon.com/2023/11/15/performance-in-composelessons-learned-from-lazy-layouts/">by 40%</a>, which is a significant argument in favor of updating. However, for already optimized lists, the performance gain may not be as noticeable.</p><p>Composition in Compose is costly, but this is the price for the convenience of the declarative approach. In this article, we will propose ways to minimize the costs of composition and reduce their impact during recompositions.</p><p>First, let’s look at how the time of composition relates to the other phases of Compose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjrK1qgJQdADpWjZ2EXjJg.png" /><figcaption>Average time of each phase. Data for a weak device. <a href="https://www.droidcon.com/2023/11/15/performance-in-composelessons-learned-from-lazy-layouts/">Source</a></figcaption></figure><p>From this graph, it becomes clear why moving work to the next phase from composition is so effective. However, we should not overlook the costs involved in creating lambdas and the potential problems with their equality when closures capture external variables. Hence, it is advisable to use them to delay frequent changes, rather than individual ones.</p><h4>Modifier.Node</h4><p>Modifier.composed has long been the primary tool for creating custom modifiers. However, despite its flexibility, this method <a href="https://www.youtube.com/watch?v=BjGX2RftXsU">has drawbacks</a>. Modifier.composed requires the inclusion of a composable lambda that generates a restartable group and several other constructs. During composition, these composable lambdas are called internally to produce the final modifier. This process, known as <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/package-summary#(androidx.compose.runtime.Composer).materialize(androidx.compose.ui.Modifier)">materialization</a>, adds to the complexity of the initial composition process. Additionally, the use of lambdas complicates the comparison of modifiers since each new lambda differs from the previous, resulting in distinct modifier chains that limit the number of skips Compose can apply.</p><p>Now, Modifier.Node offers a new, more efficient method for creating custom modifiers. This approach accomplishes all the tasks previously handled by Modifier.composed, but without the excessive overhead associated with composable lambdas and composition. The primary advantage is that classes created with Modifier.Node can be compared and reused, significantly enhancing performance.</p><p>Google has recently updated its <a href="https://developer.android.com/jetpack/compose/custom-modifiers">documentation</a> to include numerous examples and guidelines for using Modifier.Node. This update provides an excellent opportunity to review and replace existing modifier implementations in your project with the more optimized Modifier.Node.</p><h4>Problems with DerivedState and remember</h4><p>As we have already discovered, composition itself is costly, and utilizing DerivedState is advised to reduce the number of recompositions. However, it is often misused, as detailed in the first part. It is important to explain why it is crucial to pay attention to this.</p><p>Let’s examine the time it takes to read specific data to grasp the problem’s extent (<a href="https://www.droidcon.com/2023/11/15/performance-in-composelessons-learned-from-lazy-layouts/">source</a>):</p><ul><li>local variable read — 1 ns</li><li>field read — 5 ns</li><li>method call — 10 ns</li><li>synchronized read — 50 ns</li><li>map.get — 150 ns</li><li>state.value — 2,500 ns</li><li>derivedState.value — 10,000 ns</li></ul><p>Considering that to maintain a screen refresh rate of 120 fps, the maximum rendering time per frame must not exceed 8,333,333 ns, it is clear that the misuse of DerivedState can significantly decelerate your application. If this method does not lead to a noticeable reduction in recompositions, it may slow down the code more than directly accessing the original State&lt;T&gt;.</p><p>The same principle applies to the remember function. Careless memorization of simple calculations can unjustifiably slow down the application’s performance. For instance, to memorize a simple expression, it is necessary first to compare keys with their previous values, which alone is more costly, not to mention the additional overhead of reading and writing to the Slot Table.</p><pre>// Counterexample<br>val expr = remember(a, b, c) { a + b * c }</pre><p>Thus, it is beneficial to have at least a basic understanding of how Compose operates internally to avoid detrimentally leveraging its features.</p><h3>Balancing Compose with traditional Kotlin techniques</h3><p>To work effectively with Jetpack Compose, it is crucial to find a balance between utilizing Compose features and standard Kotlin code. As Compose developer Andrey Shikov noted, “While learning how to Compose, we forgot how to Kotlin”. Let’s take a look at <a href="https://www.droidcon.com/2023/11/15/performance-in-composelessons-learned-from-lazy-layouts/">his example</a> demonstrating this approach. The original version of the code utilized many separate states and side-effects:</p><pre>@Composable <br>fun MyComponent(modifier: Modifier, config: Config) {<br>    val interactionSource = remember { MutableInteractionSource() }<br>    val activeInteractions = remember { mutableStateListOf&lt;Interaction&gt;() }<br>    val config by rememberUpdatedState(config)<br><br>    LaunchedEffect(interactionSource) {<br>        interactionSource.interactions.collect {<br>            // update the interaction list<br>        }<br>    }<br><br>    val animatableColor = remember {<br>        Animatable(config.defaultColor, Color.VectorConverter)<br>    }<br><br>    LaunchedEffect(config) {<br>        // update state.animatable to new target<br>        // update state.config<br>    }<br><br>    LaunchedEffect(interactions) {<br>        snapshotFlow { activeInteractions.lastOrNull() }.collect {<br>            // update animatableColor based on interactions and configuration<br>        }<br>    }<br><br>    // use animatableColor in drawing<br>}</pre><p>This code was optimized by combining multiple states and reducing the number of side-effects by moving the logic into a single coroutine:</p><pre>@Composable <br>fun MyComponent(modifier: Modifier, config: Config) {<br>    val state = remember { MyComponentState(config) }<br><br>    LaunchedEffect(state) {<br>        state.collectUpdates()<br>    }<br><br>    SideEffect {<br>        state.config.value = config<br>    }<br><br>    // use state.animatableColor in draw<br>}</pre><p>Such refactoring resulted in a <strong>9%</strong> improvement in code performance.</p><h4>Pre-rendering</h4><p>When you first open an application screen, user wait time consists of two primary phases: data loading and UI rendering. To minimize the wait for content to appear, you can employ a pre-rendering technique.</p><p>The method involves rendering the screen in parallel with data loading, using mock data. It is crucial that the UI composition structure remains relatively unchanged after real data replaces the mock data. Given the high cost of the composition process, this approach allows the composition to “warm up” in advance, significantly reducing the time it takes for the actual content to appear on the screen.</p><p>One way to implement pre-rendering is to use a loading indicator drawn on top of the entire screen:</p><pre>ProductDetailScreen(state: ProductUiState) {<br>    // Initially, the state contains empty data for pre-rendering content<br>    ProductDetailContent(state)<br><br>    // Display the loading indicator over the content, not in place of it<br>    if (state.isLoading) {<br>        FullscreenLoader()<br>    }<br>}</pre><p>You can also add a shimmer effect to mock data using the placeholder modifier from the Accompanist library. This method does not alter the composition structure after real data is loaded and ensures a smooth visual transition. However, it requires additional adjustments of existing elements to accurately render the shimmer effect over the content.</p><p>In the context of using lazy lists, it’s important to ensure uniformity among elements with the same contentType. If the list items do not vary significantly in composition structure, it reduces the need for additional work in rebuilding the composition tree when reusing them, which also helps speed up scrolling.</p><h4>Deferred Composition</h4><p>Lazy layouts use SubcomposeLayout to determine which elements should be displayed on the screen. This is done internally during the layout phase. The entire process occurs within a single frame, which can be problematic with complex screens.</p><p>In such scenarios, the technique of deferred composition can be beneficial. It allows the element composition process to be spread across several frames, thus enhancing frame rendering speed. More details on this technique can be found in the <a href="https://www.bam.tech/en/article/android-app-performance-optimize-startup-time-with-above-the-fold-technique">linked article</a>.</p><p>Below is an example demonstrating how to defer the composition of part of the screen using the withFrameNanos method. This method, similar to delay(), suspends coroutines, but specifically, it does so right until the start of the next frame.</p><pre>@Composable<br>fun ProductDetail(productInfo: ProductInfo) {<br>    var blockState by remember { mutableStateOf(0) }<br><br>    LaunchedEffect(Unit) {<br>        while (blockState &lt; 3) {<br>            // Defer the composition of each block by one frame<br>            withFrameNanos { }<br>            blockState += 1<br>        }<br>    }<br><br>    ProductBlock0(productInfo)<br><br>    if (blockState &gt;= 1) {<br>        ProductBlock1(productInfo)<br>    }<br>    if (blockState &gt;= 2) {<br>        ProductBlock2(productInfo)<br>    }<br>    if (blockState &gt;= 3) {<br>        ProductBlock3(productInfo)<br>    }<br>}</pre><h3>Painter</h3><h4>Xml icons vs Compose icons</h4><p>When working with icons in Compose, there are two primary approaches: using XML format icons and creating icons directly with code. Let’s explore the processes and efficiencies of each method.</p><pre>// Xml icon<br>Image(<br>    painter = painterResource(R.drawable.my_icon),<br>    contentDescription = null<br>)<br><br>// Compose icon<br>Image(<br>    painter = rememberVectorPainter(Icons.Filled.Home),<br>    contentDescription = null<br>)</pre><p>For XML icons, the loading process involves a call to painterResource(R.drawable.my_icon) and includes these steps:</p><ol><li>Reading the resource from a file or retrieving it from the cache.</li><li>Transforming XML into an ImageVector.</li><li>Creating a Painter object with rememberVectorPainter().</li></ol><p>For icons directly created in Compose, the process is streamlined as follows:</p><ol><li>Calling Icons.Filled.Home immediately initiates the creation of an ImageVector object.</li><li>Creating a Painter object with rememberVectorPainter().</li></ol><p>Tests have shown that icons made with Compose load 5% to 18% faster than XML format icons. The speed of loading depends on the complexity of the icon’s structure and the size of the source file. It’s important to note that the overall impact of icons on app performance can significantly vary depending on the number of icons displayed and their use in lazy lists.</p><p>To create your own Compose icons, you can use the <a href="https://github.com/DevSrSouza/svg-to-compose">SVG to Compose</a> tool, which supports converting both SVG and XML files. It’s also important to mention that these icons reduce problems with resources when using Compose Multiplatform.</p><h4>Painter instability</h4><p>This section was intended to discuss how Painter instability affects image and icon rendering performance, and when it might be appropriate to use a wrapper class for Painter. However, with the new ability to declare external types as stable, this concern has become outdated. This development is further explored in the <a href="#5542">innovations chapter.</a></p><h4>Extracting the Painter</h4><p>Extracting the Painter creation from the list significantly improves rendering speed. This is crucial in lists where each item requires its own Painter initialization. Despite the presence of a cache for XML resources, each call still imposes additional load. Creating a single Painter for the entire list markedly reduces this load. However, similar to removing modifiers, this may impact the readability of the code.</p><p><strong>Example before optimization:</strong></p><pre>@Composable<br>fun MyList(products: ImmutableList&lt;ProductUiState&gt;) {<br>    LazyColumn {<br>        items(products) { product -&gt;<br>            // Painter inside a list item<br>            MyProductItem(product, painterResource(R.drawable.ic_menu))<br>        }<br>    }<br>}</pre><p><strong>Example after optimization:</strong></p><pre>@Composable<br>fun MyList(products: ImmutableList&lt;ProductUiState&gt;) {<br>    // Extracting Painter for the common icon from the list<br>    val menuPainter = painterResource(R.drawable.ic_menu)<br><br>    LazyColumn {<br>        items(products) { product -&gt;<br>            MyProductItem(product, menuPainter)<br>        }<br>    }<br>}</pre><p>This technique is not only effective for icons but also for other resources, although the performance gains might be less noticeable for the latter. The approach is also applicable in scenarios with frequent recomposition due to animations, where creating costly objects is generally best avoided.</p><h3>Design system</h3><p>Creating a design system is a crucial step in implementing Jetpack Compose in projects. Developers at this stage may face challenges due to limited experience with the new technology, which can lead to inefficient code in vital parts of the design system.</p><h4>Color scheme</h4><p>Traditionally, when creating a custom color palette, developers copy the approach used in MaterialTheme. However, recent <a href="https://android-review.googlesource.com/c/platform/frameworks/support/+/2733678">developer commits</a> highlight the flaws of this implementation.</p><p>In the traditional implementation, a separate State&lt;T&gt; was created for each color, leading to the need to subscribe to a state change each time it was read. This could negatively affect performance, especially if multiple colors were used in the design system.</p><p>Traditionally, each color used its own State&lt;T&gt;, requiring monitoring for changes whenever a color is used. This could negatively impact performance, particularly when the design system incorporates many colors.</p><p><strong>Example before optimization:</strong></p><pre>@Stable<br>class ColorScheme(<br>    primary: Color,<br>    onPrimary: Color,<br>) {<br>    // State&lt;T&gt; for each color<br>    var primary by mutableStateOf(primary)<br>    internal set<br>    var onPrimary by mutableStateOf(onPrimary)<br>    internal set<br>}</pre><p>Initially, this implementation had the advantage of flexibility — the ability to change each color individually without significant performance overhead. However, as practice shows, in most applications the color scheme changes only when switching between light and dark themes, not when changing individual colors individually.</p><p>Moving to using a regular data class to describe the color scheme eliminates the need for state subscriptions and improves application performance.</p><p>Originally, this implementation offered flexibility — the ability to change each color independently without significant performance costs. However, in practice, color schemes in most applications change only with the switch between light and dark themes, not with changes to individual colors.</p><p>Switching to a simple data class to describe the color scheme eliminates the need to track state changes and improves performance.</p><p><strong>Example after optimization:</strong></p><pre>@Immutable<br>data class ColorScheme(<br>    val primary: Color,<br>    val onPrimary: Color,<br>)</pre><h4>Mistakes of the Past</h4><p>The code we’re discussing was written long ago and has remained unchanged since. However, it was extensively used across all our screens and significantly impacted frame rendering times due to its inefficient handling of typography in AppTheme.</p><p>AppTheme.typography was programmed to create new typography with <strong>each invocation</strong>, loading fonts and colors from resources for each text style individually. This approach led to repeated resource calls and necessitated reading AppTheme.colors.textPrimary 16 times for each TextStyle, which was highly inefficient.</p><pre>object AppTheme {<br>    @Composable<br>    @ReadonlyComposable<br>    val typography<br>        get() = DefaultAppTypography<br>}<br><br>@Composable<br>@ReadonlyComposable<br>val DefaultAppTypography<br>    get() = AppTypography(<br>        headXXL = TextStyle(<br>            color = AppTheme.colors.textPrimary,<br>            ...<br>        ),<br>        // Creating 15 other text styles<br>    )</pre><p>This implementation notably slowed down rendering on screens with a lot of text and varied styles, as each text element triggered a call to, for example, AppTheme.typography.headXXL. We identified this issue after thoroughly analyzing several screens with <a href="https://proandroiddev.com/conscious-compose-optimization-e16144b80eef#b022">composition tracing</a>.</p><p>The solution involved changing how we create and utilize typography. Now, AppTheme typography is initialized just once and can be accessed via LocalAppTypography.current, significantly reducing resource calls and improving typography performance across the entire application:</p><pre>object AppTheme {<br>    @Composable<br>    @ReadonlyComposable<br>    val typography<br>        get() = LocalAppTypography.current<br>}</pre><h3>Formatters</h3><p>It’s crucial to correctly place the logic for formatting numbers and currencies. While it might seem convenient to incorporate formatting directly into Compose code, this can lead to unexpected performance issues. It is advisable to integrate the creation and use of formatters into your application’s business logic. This method not only lightens the load on the main thread but also prevents the redundant duplication of formatter objects, facilitating their reuse across screens. Although this recommendation may appear straightforward, it’s frequently overlooked in practice, particularly when formatting is obscured by utility functions.</p><p>Example of what not to do in Compose сode:</p><pre>Text(<br>    text = productItem.price.toMoneyFormat()<br>)</pre><p>However, bear in mind that shifting formatting to the business logic might not always yield the anticipated improvements. When processing lists in business logic, formatting is applied to the entire list at once. In contrast, within Compose, especially in the context of lazy lists, formatting is only applied to the elements visible to the user. Consequently, relocating formatting logic could potentially delay the display of content on the screen. It is important to remember that not all optimizations enhance performance, and it is crucial to thoroughly analyze any changes before implementation.</p><h3>Micro-optimizations</h3><p>These recommendations will prove useful when developing utility functions, essential application components, or creating a design system. They become particularly important when working with animations and graphics. When writing code that runs in the background and isn’t used universally, striving to use structures more efficient than the standard ones may be unnecessary. It’s important to remember that optimizing algorithmic complexity will yield a more noticeable performance boost than micro-optimizations.</p><h4>Autoboxing</h4><p>Autoboxing of primitive data types can subtly slow down code execution, especially when used extensively. In Jetpack Compose, developers actively seek to minimize such overhead by implementing various methods:</p><ul><li>Using special MutableState for primitive types (e.g., mutableIntStateOf()) helps avoid boxing.</li><li>Introducing special values (like Unspecified) for certain classes instead of null prevents auto-boxing by leveraging inline value classes. For instance, Unspecified <a href="https://issuetracker.google.com/issues/299490814">was recently added</a> for properties like TextAlign and TextDirection to avoid null.</li><li>Replacing Pair&lt;Int, Int&gt; with a value class having a Long field significantly reduces data storage costs by utilizing the stack instead of the heap. Long can store twice as many bits as Int, which enables it to hold two Int values and access them using bitwise operations.</li></ul><h4>Fast methods</h4><p>Not all standard Kotlin methods are ideally suited for specific tasks. Jetpack Compose offers alternatives such as fastForEach or fastFirst. More about these methods can be found on <a href="https://www.romainguy.dev/posts/">Romain Guy’s blog</a>.</p><h4>Effective structures</h4><p>Standard data structures in Kotlin might not be the best fit for specialized tasks.</p><ul><li>For example, mutableListOf uses ArrayList, which could be excessive if there&#39;s no need to dynamically resize the collection or use generics. In critical code sections, it is preferable to use specialized arrays, like IntArray.</li><li>The mutableMapOf method defaults to creating a LinkedHashMap, which may be less efficient than other data types. For instance, Jetpack Compose uses ScatterMap.</li></ul><p><a href="https://developer.android.com/reference/androidx/collection/package-summary">AndroidX Collections</a> contain numerous optimized structures that are advisable to use in critical code.</p><h4>Nested “if” statements</h4><p>When working with conditional constructs, it’s important to consider the performance impact of nesting. Each conditional branch generates additional calls to startReplaceableGroup and endReplaceableGroup to facilitate fast code replacement. Therefore, unless necessary, prefer a flat structure over nested conditional blocks. This approach simplifies the code and enhances performance by reducing the number of operations.</p><p><strong>Example of code generation for flat “if” statements (also applies to </strong><strong>when):</strong></p><pre>if (condition1) {<br>    $composer.startReplaceableGroup()<br>    Content1()<br>    $composer.endReplaceableGroup()<br>} else if (condition2) {<br>    $composer.startReplaceableGroup()<br>    Content2()<br>    $composer.endReplaceableGroup()<br>} else {<br>    $composer.startReplaceableGroup()<br>    Content3()<br>    $composer.endReplaceableGroup()<br>}</pre><p><strong>Example of code generation for nested “if” statements:</strong></p><pre>if (condition1) {<br>    $composer.startReplaceableGroup()<br>    Content1()<br>    $composer.endReplaceableGroup()<br>} else {<br>    $composer.startReplaceableGroup()<br>    if (condition2) {<br>        $composer.startReplaceableGroup()<br>        Content2()<br>        $composer.endReplaceableGroup()<br>    } else {<br>        $composer.startReplaceableGroup()<br>        Content3()<br>        $composer.endReplaceableGroup()<br>    }<br>    $composer.endReplaceableGroup()<br>}</pre><h3>Innovations</h3><h4>Specifying the stability of external types</h4><p>With the release of the Compose Compiler version 1.5.5, you can now explicitly <a href="https://developer.android.com/jetpack/compose/performance/stability/fix#configuration-file">specify the stability of external types</a>. This innovation eliminates the need for additional wrappers to ensure stability. We recommend adding frequently used classes such as Kotlin’s standard collections and Painter to your list of stable types. It’s essential to specify this in every module where Compose is used. This is particularly important for those who choose not to use immutable collections, either because they are still in alpha or due to the extensive code rewriting that would be required.</p><pre>// All collections from Kotlin<br>kotlin.collections.*<br><br>// Painter<br>androidx.compose.ui.graphics.painter.Painter</pre><h4>Strong skipping mode</h4><p>Currently, <a href="https://android.googlesource.com/platform/frameworks/support/+/androidx-main/compose/compiler/design/strong-skipping.md">Strong Skipping Mode</a> is experimental and can be activated through a special flag. It may become the default setting in the future. Here’s what it offers:</p><ul><li>All restartable functions become skippable. For unstable parameters, comparison is by instances; for stable ones, it’s by equals.</li><li>Lambdas capturing unstable variables are also wrapped in remember.</li></ul><h3>Toolkit</h3><h4>Viewing Compose source code</h4><p>Whenever you are unsure about how certain code will function after being compiled by Compose, it’s advisable to examine the final Java code. Even if you are well-versed in Compose code generation from Jetpack Compose Internals or various articles, this does not protect you from potentially outdated information. For this purpose, there is a convenient Gradle plugin called <a href="https://github.com/takahirom/decomposer/">decomposer</a>.</p><h4>Vkompose plugin</h4><p>Among the useful tools are <a href="https://github.com/VKCOM/vkompose">plugins from VK for Kotlin and IDE</a> that:</p><ul><li>Highlight unstable parameters and functions that cannot be skipped directly in the IDE.</li><li>Visually indicate ongoing recompositions in the UI with colored borders.</li><li>Log the reasons for recompositions.</li></ul><h4>Detekt</h4><p>Detekt not only helps monitor code style but also guards against poor practices that lead to performance degradation, including:</p><ul><li><a href="https://mrmans0n.github.io/compose-rules/rules/">compose-rules</a> — a large list of diverse rules.</li><li><a href="https://github.com/VKCOM/vkompose">vkompose</a> — offers a rule in addition to the plugin that checks the skippability of functions.</li></ul><h3>Summary</h3><p>In summary, we’ve learned how to tackle issues with the initial setup in Compose and why it’s crucial not to burden it with unnecessary logic, as convenience and simplicity do come at a cost. However, thanks to the relentless efforts of the developers, Compose’s performance has significantly improved, allowing us to divert our attention to other development aspects. Screens with huge DAU, even when built on traditional View systems, have required optimization beyond standard methods. For Compose, the limits are far from being reached: <a href="https://developer.android.com/jetpack/androidx/compose-roadmap">future optimizations</a> will make it an even more powerful tool, perfectly equipped for any task.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3e42ce3069d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/conscious-compose-optimization-2-tackling-composition-f3e42ce3069d">Conscious Compose optimization 2: Tackling composition</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conscious Compose optimization]]></title>
            <link>https://proandroiddev.com/conscious-compose-optimization-e16144b80eef?source=rss-d9d9fd536586------2</link>
            <guid isPermaLink="false">https://medium.com/p/e16144b80eef</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Andrey Bogomolov]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 17:54:06 GMT</pubDate>
            <atom:updated>2024-07-25T14:05:45.385Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dN3jFHy7fb_gSfHXETcyPg.png" /><figcaption>Image from <a href="https://habr.com/ru/companies/ozontech/articles/742854/">Ozon Tech blog on Habr</a></figcaption></figure><p>Jetpack Compose is a relatively young technology for writing declarative UI. Many developers don’t even realize that they are writing suboptimal code in such a critical part, and later it leads to unexpected poor performance and falling metrics.</p><p>Our Ozon Seller team also faced this problem. We decided to put together all the tips and tricks for writing optimized Compose code. Active application of these tips when optimizing existing screens and writing new ones has significantly improved our metrics: the lag duration in relation to the scroll duration (hitch rate; the less the better) of screens with lists has dropped from 15–19% to 5–7% on average (at the 90th percentile). We have described all these tips and tricks in this article. It will be useful for both beginners and experienced developers, it describes optimizations and Compose mechanisms in detail, and also tells you about poorly documented features and corrects mistakes that can be found in other articles. Let’s get started.</p><p>Article series:</p><p>1. Conscious Compose optimization (current) (<a href="https://habr.com/p/742854/">original</a>)<br>2. <a href="https://proandroiddev.com/conscious-compose-optimization-2-tackling-composition-f3e42ce3069d">Conscious Compose optimization 2: Tackling composition</a> (<a href="https://habr.com/p/796437/">original</a>)</p><h4>Table of content</h4><ul><li><a href="#">Introduction</a></li><li><a href="#2630">Composable functions</a><br>– <a href="#c695">Main idea</a><br>– <a href="#7f9e">Compose Phases</a><br>– <a href="#1fbb">Parameters in composable functions</a></li><li><a href="#208e">Stable types</a><br>– <a href="#91ab">Classification of types by stability</a><br>– <a href="#df10">@Immutable and @Stable</a><br>– <a href="#989a">Skippability of the functions</a><br>– <a href="#039b">Lambdas</a></li><li><a href="#8984">Skip optimization</a><br>– <a href="#099e">Restartable functions</a><br>– <a href="#d8b2">Restartability and skippability</a><br>– <a href="#0cb1">When restartability and skippability are not needed</a><br>– <a href="#10af">Optimization of frequently changing elements</a><br> - <a href="#3c14">Derived state</a><br> - <a href="#bf38">Deferred reading of states in composable functions</a><br> - <a href="#edc3">Deferred reading of states in Compose phases</a><br>– <a href="#1686">Reducing the recomposition area</a><br>– <a href="#1892">Using key and contentType in lists</a><br>– <a href="#d45c">Modifiers</a><br> - <a href="#cdcc">Custom modifiers</a><br> - <a href="#6c9b">Reusing modifiers</a></li><li><a href="#28d9">Long calculations during recomposition</a><br>– <a href="#4b47">Long calculations only in ViewModel or in remember</a><br>– <a href="#e691">Without long calculations in the UI State getters</a><br>– <a href="#8b0b">When to use remember</a></li><li><a href="#fced">Layout</a><br>– <a href="#70a2">Custom Layouts</a><br>– <a href="#75f5">Unreasonable change in size and position</a><br>– <a href="#3d48">Layout pre-calculation</a><br> - <a href="#4315">SubcomposeLayout</a><br> - <a href="#8dd8">Intrinsic measurements</a><br> - <a href="#d8f0">LookaheadLayout</a></li><li><a href="#7fdd">Other tips</a><br>– <a href="#0864">Avoid backwards writes</a><br>– <a href="#3880">MovableContentOf</a><br>– <a href="#53bb">staticCompositionLocalOf and compositionLocalOf</a><br>– <a href="#f6c2">@ReadOnlyComposable</a><br>– <a href="#9334">Use less ComposeView</a><br>– <a href="#b647">Use the latest version of Compose</a><br>– <a href="#608b">Baseline Profiles</a></li><li><a href="#b42a">Debugging and performance monitoring</a><br>– <a href="#c893">Stability and skippability testing</a><br>– <a href="#dac4">Debugging recomposition</a><br>– <a href="#b022">Composition tracing</a><br>– <a href="#14c0">Benchmarking</a></li><li><a href="#690b">Summary</a><br>– <a href="#3ffd">Cheat sheet</a></li></ul><h3>Composable functions</h3><p>First, let’s dive a little deeper into how Compose works and what it can do. This will help us understand why specific optimizations are needed and how they work.</p><h4>Main idea</h4><p>Building a UI tree is the main idea behind composable functions. Passing from the beginning to the end of the User() function, we will get a tree as in the picture:</p><pre>@Composable<br>fun User() {<br>    Row {<br>        Image()<br>        Column {<br>            Text()<br>            Text()<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*OX7UMEed3qkzHP_H" /><figcaption>Example tree of UI elements</figcaption></figure><p>To build such trees, you need more than just declarative code. The Compose compiler takes care of that for us.</p><p>The Compose compiler is a plugin for the Kotlin compiler. And this means that, unlike the kapt/ksp plugin, it can <a href="https://kotlinlang.org/docs/ksp-why-ksp.html#comparison-to-kotlinc-compiler-plugins">modify the current code</a>, and not just generate a new one. At compile time, it replaces composable functions with new ones, to which it adds auxiliary constructs and parameters, among which $composer is especially important. It can be thought of as a calling context. And the process of converting a composable-function can be thought of as what Kotlin itself does with suspend functions.</p><p>The Compose compiler adds $composer method calls at the beginning and end of the generated composable function (see code below). These methods start and end a group, which can be thought of as a node in the tree that Compose builds. That is, the beginning and end of the function are the beginning and end of the node description. The word Restart refers to the type of the group. In this article we will not dive deep into group types, but if you are interested, you can read about it in the book “Jetpack Compose internals” (Chapter 2. “The Compose compiler”, paragraph “Control flow group generation”).</p><pre>@Composable<br>fun User($composer: Composer) {<br>    $composer.startRestartGroup() // Start of group<br><br>    // Function body<br><br>    $composer.endRestartGroup() // End of group<br>}</pre><p>Based on the data from the function body, $composer builds the tree step by step. This is the first phase of Compose — <strong>Composition</strong>.</p><h4>Compose Phases</h4><p>Like most other UI toolkits, Compose renders a frame through several distinct phases.</p><p>If we look at the Android View system, it has three main phases: measure, layout, and drawing. Compose has similar phases:</p><ol><li><strong>Composition</strong>: <em>What</em> UI to show. Compose runs composable functions and creates a description of your UI.</li><li><strong>Layout</strong>: <em>Where</em> to place UI. This phase consists of two steps: measurement and placement. Layout elements measure and place themselves and any child elements in 2D coordinates, for each node in the layout tree.</li><li><strong>Drawing</strong>: <em>How</em> it renders. UI elements draw into a Canvas, usually a device screen.</li></ol><p>These three phases are executed for almost every frame, but to improve performance, Compose can skip some phases if the data for them has not changed.</p><p>The conditions for calling phases, as well as examples of places for reading the state, can be seen in the picture below. We’ll talk about reading state later, for now just think of it as getting the value of muatbleStateOf(). You can read more about phases at <a href="https://developer.android.com/jetpack/compose/phases">Android Developers</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8P5_bCeKjjl54idj" /><figcaption>Jetpack Compose phases. <a href="https://developer.android.com/jetpack/compose/phases">Source</a></figcaption></figure><h4>Parameters in composable functions</h4><p>Compose encourages us to write <a href="https://jorgecastillo.dev/kotlin-purity-and-function-memoization">pure functions</a>. This makes them more deterministic and also allows Compose developers to make the first optimization — simply not to execute a composable function if the arguments haven’t changed.</p><p>Let’s immediately introduce such concepts as <strong>composition</strong> — building a tree of composable functions, and <strong>recomposition</strong> — updating this tree when the data changes.</p><p>We have come to another parameter that the Compose compiler adds to composable functions — $changed. It is just an Integer number, which is a bitmap where bits are responsible for information about the arguments of a composable function and their changes.</p><pre>// Parameters of a composable function after running the Compose compiler <br>@Composable<br>fun Header(text: String, $composer: Composer&lt;*&gt;, $changed: Int)</pre><p>If some parameters have changed in the parent composable function, and some remain the same, then the information about the comparison is passed to the child functions as the $changed parameter so that they do not make unnecessary comparisons. The functions themselves compare only arguments that the parent is not sure about, or if the arguments are set by default.</p><p>Mutable arguments — objects that are able to change (modify their data) — can kill the whole point of comparison. To solve this problem, the Compose developers decided to separate all types into stable and unstable. If all the arguments of a function are stable and have not changed, the recomposition is skipped, otherwise you will have to restart the function again.</p><p>A function that supports skipping recomposition is called <strong>skippable</strong>. We should try to make almost all of our functions skippable. This will have a very good effect on optimization.</p><h3>Stable types</h3><h4>Classification of types by stability</h4><p>The Compose compiler walks through all types and adds stability information to them: the @StabilityInferred annotation and the $stable static field with type stability information.</p><p>Type stability means that the Compose runtime can safely read and compare input of that type to skip recomposition if necessary. The ultimate goal of stability is to help the Compose runtime.</p><p><strong>Stable </strong>types are:</p><ul><li>All primitive types and String.</li><li>Functional types (lambdas) (that’s why the concept of “unstable lambdas” is not quite correct, but more on that below).</li><li>Classes with all fields of stable type and declared as val, including sealed classes. Stability of class fields is checked recursively until a type is found whose stability is already unambiguously known.</li><li>Enum (even if you specify a var field and change it).</li><li>Types marked @Immutable or @Stable.</li></ul><p>All stable types must fulfill a certain contract, which we will discuss next.</p><p>Compose considers <strong>unstable</strong>:</p><ul><li>Classes with at least one field of unstable type or declared as var.</li><li>All classes from external modules and libraries that do not have a Compose compiler (List, Set, Map and other collections, LocalDate, LocalTime, Flow…).</li></ul><p>For <strong>generics </strong>(MyClass&lt;T&gt;), the check is based on the structure of the generic itself, and then on the specified type. If the generic’s structure is unstable (there are fields of unstable type or fields with var), it is immediately considered unstable. If we specify the generic’s type right away, Compose will determine it as stable or unstable at the compilation stage:</p><pre>// Stable<br>class MyClassStable(<br>    val counter: Pair&lt;Int, Int&gt;<br>)<br><br>// Unstable<br>class MyClassUnstable(<br>    val counter: Pair&lt;LocalDate, LocalDate&gt;<br>)<br><br>// Unstable<br>class MyClassUnstable(<br>    val counter: Pair&lt;*, *&gt;<br>)</pre><p>If we make a composable generic function and pass the generic to it as argument (@Composable fun &lt;T&gt; Item(arg: Pair&lt;T, T&gt;)), then the behavior will be the same as for types with computable stability, which we will talk about further.</p><p>The Compose developers have also <strong>predefined</strong> <a href="https://cs.android.com/android-studio/kotlin/+/master:plugins/compose/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/analysis/KnownStableConstructs.kt">external types</a> that will be considered stable: Pair, Result, Comparator, ClosedRange, collections from the <a href="https://github.com/Kotlin/kotlinx.collections.immutable">kotlinx.collections.immutable</a> library, dagger.Lazy and others. Most of these types are generics, so this list only tells us about the stability of their structure. That is, if we pass a stable type to these generics, they will be stable, and if unstable, they will be unstable. It can be said that the principle that all classes from external modules and libraries that do not have a Compose compiler are unstable will simply not apply to these types.</p><p>There are also types with <strong>computable stability</strong> — about which Compose cannot say at compile time that they are unambiguously stable or unstable. Their stability is checked already at runtime, when specific objects are received. Such types include:</p><ul><li>Types that are declared in other modules with Compose compiler enabled. If we use a type from module 2 where Compose <strong>is not enabled<em> </em></strong>in module 1, then the Compose compiler simply cannot check this type for stability, so it will immediately consider it unstable. And if Compose <strong>is enabled</strong> in module 2, the Compose compiler assumes that it will check this type in module 2: it will annotate it with @StabilityInferred and add a static field $stable. And then it will read this field at runtime, not at compile time.</li><li>Interfaces (the check is based on the derived class, the object of which will be passed as argument).</li></ul><blockquote>About stability of interfaces:<em> <br>Some other articles and sources write that interfaces are unstable, but according to </em><a href="https://cs.android.com/android-studio/kotlin/+/master:plugins/compose/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/analysis/Stability.kt;l=280"><em>Compose source code</em></a><em>, output metrics and test results we came to the conclusion that interface stability is calculated at runtime. In the tests they are marked as Uncertain (which correlates with the </em><a href="https://cs.android.com/android-studio/kotlin/+/master:plugins/compose/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/analysis/Stability.kt;l=93"><em>Unknown</em></a><em> class). At the same time, the types that Compose is certain about are correlated with the </em><a href="https://cs.android.com/android-studio/kotlin/+/master:plugins/compose/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/analysis/Stability.kt;l=79"><em>Certain</em></a><em> class (</em><em>Stable or </em><em>Unstable). The totality of all these arguments led me to this conclusion.</em></blockquote><p>Additionally, you can find out the stability of types in <a href="https://cs.android.com/android-studio/kotlin/+/master:plugins/compose/compiler-hosted/integration-tests/src/jvmTest/kotlin/androidx/compose/compiler/plugins/kotlin/ClassStabilityTransformTests.kt">tests</a> or in composable metrics, which are described in the chapter on debugging.</p><h4>@Immutable and @Stable</h4><p>If you are sure that a class or interface and all its descendants are stable, you can annotate them with @Immutable if they are immutable, or @Stable if they can change but notify Compose of their change. For example, @Stable is suitable if the class has a field of type State&lt;T&gt; or MutableState&lt;T&gt; (mutableStateOf() creates such an object).</p><pre>@Immutable<br>data class MyUiState1(val items: List&lt;String&gt;)<br><br>@Stable<br>data class MyUiState2(val timer: MutableState&lt;Int&gt;)</pre><p>Stability from such annotations is inherited by child types.</p><pre>@Immutable<br>interface Parent // Stable type<br><br>class Child1(val age: Int) : Parent // Stable type<br><br>class Child2(var list: List&lt;String&gt;) : Parent // Also the stable type</pre><p>The @Immutable and @Stable annotations are useful to mark types that Compose thinks are unstable, but in fact are stable, or you are sure that they will be used as stable.</p><p>Both annotations currently just perform the logic of a stable type declaration and are the same for Compose, but it is still desirable to use them as intended, as Compose developers may change the behavior in the future.</p><p>By marking type with these annotations, you promise Compose that your type will fulfill the following contract:</p><ol><li>The result of equals will always return the same result for the same two instances.</li><li>When a public property of the type changes, composition will be notified.</li><li>All public property types are stable.</li></ol><p>This contract is just your promise, and Compose will not check in any way if you break it. But then unexpected behavior of composable functions is possible. Let’s look at the contract in detail.</p><p>The first point is especially important and can shoot, even if you make all arguments stable. For example, in the code below we see that MyUiState doesn’t have an overridden equals like the data class, which means that the check will be done by reference. If MyComposable1 is recomposed, then MyUiState will be recreated. When checking by reference, Compose will consider it a completely different object and will not skip MyComposable2, although the field remains the same.</p><pre>class MyUiState(val name: String)<br><br>@Composable<br>fun MyComposable1() {<br>    val myState = MyUiState(&quot;Name&quot;)<br>    MyComposable2(myState)<br>}<br><br>@Composable<br>fun MyComposable2(uiState: MyUiState) {<br>    Text(uiState)<br>}</pre><p>This situation is solved either by writing your own implementation of equals (or using data class), or by remembering this object with remember so that it won’t be recreated during recomposition (or similar actions in business logic if the object is recreated there).</p><p>The second point is implemented in State&lt;T&gt; and MutableState&lt;T&gt; (mutableStateOf), which under the hood notifies Compose when it changed.</p><p>The third point of the contract implies that you use public fields as stable fields. That is, if you have a field of formally unstable type List&lt;T&gt; and you don’t cast it somewhere to MutableList&lt;T&gt;, then feel free to mark your class as @Immutable or @Stable.</p><p>@Stable can also be applied to regular (non-composable) functions and properties. Then Compose will assume that they will return the same value if the arguments have not changed. The annotation does not affect composable functions. It is mainly needed to optimize the generated code for default arguments in composable functions.</p><p>Examples of functions and properties marked with @Stable: Modifier.padding(), Modifier.width(), Int.dp; transition functions in animations: fadeIn(), fadeOut(), slideIn().</p><blockquote>About the influence of @Stable on functions and properties:</blockquote><blockquote><em>In composable metrics, you can see the impact of annotation by how the Compose compiler marks default arguments: </em><em>@dynamic or </em><em>@static. Briefly, with </em><em>@static in the default arguments, composable functions are not called and states that can trigger recomposition are not read (more on this below). You can read more about </em><em>@dynamic and </em><em>@static </em><a href="https://github.com/androidx/androidx/blob/androidx-main/compose/compiler/design/compiler-metrics.md#default-parameter-expressions-that-are-dynamic"><em>at the link</em></a><em>.</em></blockquote><blockquote><em>During our experiments we could not get a specific effect (e.g. skipping) in the function from marking </em><em>@Stable, only the metrics changed from </em><em>@dynamic to </em><em>@static.</em></blockquote><pre>@Composable<br>fun MyWidget(param1: String, param2: String = testStable()) {<br>    Text(param1 + param2)<br>}<br><br>@Stable<br>fun testStable() = &quot;test&quot;<br><br>// Composable metric for the function<br>restartable skippable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun MyWidget(<br>  stable param1: String,<br>  stable modifier: String? = @static testStable()<br>)</pre><h4>Skippability of the functions</h4><p>Compose makes a composable function skippable only if all its parameters are of stable type and the function returns Unit. Unstable parameters are ignored if they are not used in the body.</p><p>For skipped functions, Compose specifically generates code to prevent them from being called again if the input data has not changed.</p><pre>@Composable<br>fun Header(text: String, $composer: Composer&lt;*&gt;, $changed: Int) {<br>    if (/* Skip check logic */) {<br>        Text(text) // Function body is executed<br>    } else {<br>        $composer.skipToGroupEnd() // Letting Compose know that we skipped a function<br>    }<br>}</pre><p>Unstable types are also found among the frequently used types in Compose, for example, Painter, so you should be careful to use it to not lose skippability in the function.</p><p>If there are arguments with runtime-computed stability, the function remains skippable, but additionally code is generated that does not skip it if the argument turns out to be of an unstable type at runtime.</p><p>Based on the above, we in the team agreed to mark all UI models and states as @Immutable or @Stable, since we initially design them as such. We especially keep an eye on stability when developing a UI kit project, as the cost of an error becomes higher. To check type stability, you can use Compose metrics (we will return to them at the end of the article).</p><p>You can also simply pass as little unnecessary data as possible to the functions. It’s simple: less data — less probability that they will change.</p><p>What to do if you need to use standard collections or external classes and want functions to be skippable? So far, the space of possibilities is very limited: either make a wrapper class (value class can also be used as a wrapper) and mark it as @Immutable or @Stable, or simply avoid it. For standard collections there is an option to switch to collections from kotlinx.collections.immutable in UI-models. The ability to declare stability of external types is in the plans of Compose developers.</p><h4>Lambdas</h4><p>Let’s talk about how lambdas work in Compose and how to prepare them properly. This <a href="https://multithreaded.stitchfix.com/blog/2022/08/05/jetpack-compose-recomposition/">article</a> gives an interesting example of invoking the ViewModel method inside a lambda, which leads to unnecessary recompositions.</p><p>Briefly, this situation can be summarized as follows:</p><pre>@Composable<br>fun MyScreen() {<br>    val viewModel = remember { MyViewModel() }<br>    val state by viewModel.state.collectAsState()<br> <br>    MyComposableItem(<br>        name = state.name,<br>        onButtonClick = { viewModel.onAction() }<br>    )<br>}</pre><p>To understand what and why, let’s take a look at how Compose handles lambdas. It divides them into non-composable, in which composable code is not executed, and composable respectively. Let’s consider the first type in detail.</p><p>Non-composable lambdas that are created in a composable function are wrapped in remember { } at compile time. All captured variables are put as a key for remember:</p><pre>// Before compilation<br>val number: Int = 6<br>val lambda = { Log.d(TAG, &quot;number = $number&quot; }<br><br>// After compilation<br>val number: Int = 6<br>val lambda = remember(number) { { Log.d(TAG, &quot;number = $number&quot; } }</pre><p>If a lambda captures a variable whose type is <strong>NOT stable</strong> (i.e. unstable or computable in runtime: the condition is stricter than for skippability) or the variable is declared as var, Compose does not wrap it in remember, which causes it to be recreated during recomposition. Further, when comparing the past and current lambda, Compose will find out that they are not equal, and because of this it will start recomposition of even the skippable function (it is assumed that MyViewModel is an unstable type).</p><p>How to solve this problem? Method reference (viewModel::onAction) used to work, but since Compose 1.4 it stopped working due to using reference comparison instead of the custom equals that Kotlin generates. You can read more in <a href="https://twitter.com/shikasd_/status/1601180953476755456?t=Rl5XqCBepAhE6sNT8WP97w&amp;s=19">this thread</a>, as well as in <a href="https://www.droidcon.com/2022/11/15/understanding-recomposition-performance-pitfalls/">this video</a> from 32:50.</p><p>Methods that work:</p><ul><li>Remember the lambda yourself (in this case, the key itself must not change with each recomposition):</li></ul><pre>val onAction = remember { { viewModel.onAction() } }</pre><p>You can do it this way (why remember the lambda and not the method reference, you can read <a href="https://vtsen.hashnode.dev/prefer-function-reference-over-lambda-in-kotlin-wrong">here</a>):</p><pre>@Composable<br>inline fun &lt;T : Any&gt; MviViewModel.rememberOnAction(): ((T) -&gt; Unit) {<br>    return remember { { this.onAction(it) } }<br>}<br><br>val onAction = viewModel.remberOnAction()</pre><ul><li>Use top-level (static) functions and variables. Here, the Kotlin compiler will call them directly since they are static, rather than passing them through the class constructor that will be created for the lambda at compile time.</li><li>Use only stable external variables inside the lambda.</li><li>Use arguments received from within the lambda. This may not help, only postpone or reduce the problem, but it will definitely help if you used to capture a list and now you won’t capture anything.</li></ul><pre>@Composable<br>fun MyComposableItem(items: List&lt;MyClass&gt;) {<br>    // Instead of this<br>    ItemWidget { items[5].doSomething() } <br> <br>    // Do this<br>    ItemWidget(item[5]) { item -&gt; item.doSomething() }<br>}</pre><p>A lambda can also implicitly capture an external variable if you in the lambda call a function from a fragment in a composable function. Then the lambda constructor will take the fragment as an argument, and remember around the lambda will not be generated.</p><pre>class MyFragment : Fragment {<br>    fun onButtonClick() { ... }<br><br>    @Composable<br>    fun Screen() {<br>        MyButton(onClick = { onButtonClick() })<br>    }<br>}</pre><p>You might also have a question, how does remember { } handle the lambda itself if it accepts a lambda? The fact is that remember is an inline function, and its lambda turns into a regular code block. So, function:</p><pre>val resultValue = remember(key1, key2) {<br>    // Our calculations (e.g. creating a lambda)<br>}</pre><p>will turn into the following code:</p><pre>// Retrieving a remembered value<br>val rememberedValue = composer.rememberedValue()<br><br>val needUpdate = /* Checking if our keys key1 and key2 have changed,<br>    or the value has not yet been initialized */<br><br>if (needUpdate) {<br>    // Our calculations. Inline lambda will turn into a code block<br>    val value = calculation() <br><br>    // Updating the remembered value<br>    composer.updateRememberedValue(value) <br><br>    return value // Returns the calculated and remembered value<br>} else {<br>    return rememberedValue // Returns the remembered value<br>}</pre><p><em>The code above only reflects the logic and has omissions.</em></p><p>In addition, you can see more about lambdas under the hood in the context of Compose in <a href="https://www.droidcon.com/2022/11/15/understanding-recomposition-performance-pitfalls/">this video</a> from 25 minutes.</p><h3>Skip optimization</h3><h4>Restartable functions</h4><p>First, let’s understand what the restartable composable functions are. As mentioned above, $composer starts and ends a group — conventionally a node in the tree — at the beginning and end of the function. For restartable functions, the restartable group is called:</p><pre>@Composable<br>fun MyComposable($composer: Composer) {<br>    $composer.startRestartGroup() // Group start<br><br>    // Function body<br><br>    $composer.endRestartGroup() // Group end<br>        ?.updateScope { $composer -&gt;<br>            MyComposable($composer)<br>        }<br>}</pre><p>At the end of the code you can see the mechanism of restarting the function on change: if between the beginning and the end of the group there was read a state that can notify Compose about its change (State&lt;T&gt; or CompositionLocal), then $composer.endRestartGroup() will return not null and Compose will learn to restart our function. If there is a restartable group closer to the state reading location, then it is this group that will be restarted, and not the outer one.</p><p>Let’s look at this code:</p><pre>@Composable<br>fun MyComposable1() {<br>    val counter: MutableState&lt;Int&gt; = remember { mutableStateOf(0) }<br>    MyComposable2(counter)<br>}<br><br>@Composable<br>fun MyComposable2(counter: State&lt;Int&gt;) {<br>    Text(text = &quot;My counter = ${counter.value}&quot;)<br>}</pre><p>In it, when the counter changes, only MyComposable2 will be restarted, since the value is read in its scope. The same MutableState can be imagined as MutableStateFlow, which performs the necessary subscription and notification logic under the hood when reading and writing. This is a very important logic of how Compose works, since it is MyComposable2 that will restart without touching the other parent functions. This is what the recomposition mechanism is based on. Together with the skipping mechanism, it gives a wide range of optimization possibilities, especially for frequently changing parts of the UI.</p><p>To consolidate the chapter, here are more examples that will cause MyComposable2 to be a restart (recomposition) point and go through all its children, while MyComposable1 will not be affected. It may be added that animateColorAsState(), rememberScrollState(), etc. also contain State&lt;T&gt; inside, and can cause recomposition when changed.</p><pre>val LocalContentAlpha = compositionLocalOf { 1f }<br><br>@Composable<br>fun MyComposable1() {<br>    val counter1: MutableState&lt;Int&gt; = remember { mutableStateOf(0) }<br>    var counter2: Int by remember { mutableStateOf(0) }<br>    MyComposable2(counter1, { counter2 })<br>}<br><br>@Composable<br>fun MyComposable2(counter1: State&lt;Int&gt;, counterProvider2: () -&gt; Int) {<br>    Text(&quot;Counter = ${counter1.value}&quot;) // Reading the state<br>    Text(&quot;Counter = ${counterProvider2()}&quot;) // Reading the state<br>    Text(&quot;Counter = ${LocalContentAlpha.current}&quot;) // Reading the state<br>}</pre><p>Note that if you are using State&lt;T&gt; as a delegate, then be careful about accidentally reading the state, especially if it changes frequently.</p><pre>@Composable<br>fun MyComposable1()<br>    var counter: Int by remember { mutableStateOf(0) }<br><br>    // Reading the state will happen in MyComposable1, not in MyComposable2!!!<br>    MyComposable2(counter) <br>}</pre><p>The Compose developers advise passing not a State&lt;T&gt;, but a lambda, as there may be difficulties and unnecessary code if something needs to be hardcoded or during testing. But, in general, there are no cardinal differences. Why all this is necessary — we’ll tell you in the chapter about deferred state reading.</p><p>It should also be noted that composable lambdas, often used in <a href="https://developer.android.com/jetpack/compose/layouts/basics#slot-based-layouts">Slot API</a>, are also restartable and skippable.</p><h4>Restartability and skippability</h4><p>So that you don’t get confused by these two terms, I’ll summarize here:</p><ul><li><strong>A restartable function</strong> can be restarted, be a restart scope.</li><li><strong>A skippable function</strong> can be skipped if its arguments haven’t changed.</li></ul><p>This is how Compose refers to functions that are both restartable and skippable in its metrics:</p><pre>restartable skippable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun MyWidget(<br>  stable widget: WidgetUiModel,<br>  stable modifier: Modifier? = @static Companion<br>)</pre><p>If at least one argument is unstable, the function will remain only restartable.</p><p>If the function is only restartable, you should either make it skippable or get rid of restartability. The @NonRestartableComposable annotation removes restartability and (if present) skippability.</p><h4>When restartability and skippability are not needed</h4><p>All inline composable functions are non restartable (Box, Column and Row). This means that reading State&lt;T&gt; inside one of them will cause recomposition in the nearest external restartable function when the state changes.</p><pre>@Composable<br>fun MyComposable() {<br>    val counter: MutableState&lt;Int&gt; = remember { mutableStateOf(0) }<br>    Box {<br>        // The recomposition will affect the entire MyComposable() <br>        // since the code will be inlined<br>        Text(text = &quot;My counter = ${counter.value}&quot;)<br>    }<br>}</pre><p>Functions that do not return Unit are also not skippable.</p><p>There are situations when skippability and restartability do not give real advantages but only lead to an excessive waste of resources:</p><ul><li>composable function data rarely or never changes;</li><li>composable function simply calls other skippable composable functions:<br>– function without complex logic and without State&lt;T&gt;, calling a minimum of other composable functions;<br>– wrapper around another function — serves as a kind of parameter mapper or to hide unnecessary parameters.</li></ul><p>In this case, you can mark the composable function with the @NonRestartableComposable annotation, which will remove restartability (and with it, skippability).</p><pre>@Composable<br>@NonRestartableComposable<br>fun ColumnScope.SpacerHeight(height: Dp) {<br>    Spacer(modifier = Modifier.height(height))<br>}</pre><p>If a function contains branching logic (if, when), then follow the above rules with respect to its branches. Whether to add annotation or not depends on how often the branches will change during use and how complex the code in each branch is.</p><p>As an example, with the @NonRestartableComposable annotation Comose developers marked Spacer (no logic and just a Layout call), some Image and Icon overloads (parameter mapping to its overload), Card (parameter mapping to Surface). The benefit of not restarting the function is minimal: no extra code is generated and no extra logic is executed, but if you are designing a UI kit, it is worth thinking about it, since your elements will be used in many places, often repeated, and in total it will give an effect .</p><h4>Optimization of frequently changing elements</h4><p>You should optimize reading of State&lt;T&gt; only where the state changes frequently and affects a lot of content. Otherwise the whole code will be overoptimized and become unusable for reading and development.</p><h4>Derived state</h4><p>derivedStateOf — derived (computed) state, which reflects the main use case.</p><pre>val listState = rememberLazyListState() <br>val showButton by remember { <br>    derivedStateOf { listState.firstVisibleItemIndex &gt; 0 } <br>}</pre><p>Let’s say we have a list state where we read the index of the first visible element of the list. But we don’t need it by itself, we want to know whether to show us the button or not. To recompose only when the visibility of the button changes, instead of every time the first visible element of the list changes, we can read the state inside the derivedStateOf lambda. There, Derived state subscribes to the state changes that were read in the first pass and returns a final State&lt;T&gt;, which already causes recomposition only when the final state changes.</p><p>It is important that the Derived state responds to changes only to the State&lt;T&gt;, and not to ordinary variables, since the State&lt;T&gt; has the functionality to subscribe and notify changes to the Compose snapshot system that Derived state works with.</p><p>Let us emphasize that you should not use the value of a frequently changing state as the remember key, otherwise the whole meaning of Derived state will be lost and recomposition in this place will occur frequently, as well as recreation of Derived state:</p><pre>// Don&#39;t do<br>val listState = rememberMyListState() <br>val showButton by remember(listState.value) { // Reading the listState<br>    derivedStateOf { listState.value &gt; 0 } <br>}<br><br>// Don&#39;t do<br>val listState by rememberMyListState() <br>val showButton by remember(listState) { // Reading the listState<br>    derivedStateOf { listState &gt; 0 } <br>}</pre><p>Derived state should only be used when the derived state will change less frequently than the original states:</p><pre>// Don&#39;t do<br>val derivedScrollOffset by remember { <br>    derivedStateOf { scrollOffset - 10f } <br>}</pre><p>Derived state is useful for wrapping states of lazy list scrolling, swiping, and other frequently changing states. A few more examples:</p><ul><li>Keeping track of whether scrolling crosses a threshold (scrollPosition &gt; 0).</li><li>The number of items in the list is greater than the threshold (items &gt; 0).</li><li>Form validation (username.isValid()).</li></ul><p>For nested Derived states, it is periodically necessary to specify a mutation policy to avoid recalculating the expression when the first (nested) derivedStateOf is changed.</p><pre>val showScrollToTop by remember {<br>    // Mutation policy — structuralEqualityPolicy()<br>    derivedStateOf(structuralEqualityPolicy()) { scroll0ffset &gt; 0f }<br>}<br><br>var buttonHeight by remember {<br>    derivedStateOf { <br>        // By specifying a mutation policy in showScrollToTop, <br>        // this calculation block will only be called when showScrollToTop changes<br>        if (showScrollToTop) 100f else 0f <br>    }<br>}</pre><p>Read more about mutation policies in <a href="https://blog.shreyaspatil.dev/leveraging-the-snapshot-mutation-policies-of-jetpack-compose">this article</a>.</p><h4>Deferred reading of states in composable functions</h4><p>The previous paragraph described the principle that Derived state uses: it reads state internally and prevents it from recomposing the whole function. We can use the same principle, but to defer reading the state from the parent function to the child function. This should also be done only for frequently changing states. You can defer reading using a lambda or passing a State and reading it in the right place.</p><pre>@Composable<br>fun MyComposable1() {<br>    val scrollState = rememberScrollState()<br>    val counter = remember { mutableStateOf(0) }<br><br>    MyList(scrollState)<br>    MyComposable2(counter1, { scrollState.value })<br>}<br><br>@Composable<br>fun MyComposable2(counter: State&lt;Int&gt;, scrollProvider: () -&gt; Int) {<br>    // Reading the state in MyComposable2<br>    Text(text = &quot;My counter = ${counter.value}&quot;)<br>    Text(text = &quot;My scroll = ${scrollProvider()}&quot;)<br>}</pre><p>In the code above, only the MyComposable2 function will be recomposed because of the fast counter or scrolling, not the entire MyComposable1.</p><h4>Deferred reading of states in Compose phases</h4><p>You can defer state reading not only between composable functions, but also between Compose phases (Composition → Layout → Drawing). For example, if we have frequent color changes, it’s better to use drawBehind {} instead of the background() modifier, which takes a lambda and will call code due the state changes only in the drawing phase, not the composition phase like background().</p><p>You can use a similar thing when scrolling: the offset {} modifier with lambda instead of simple offset(value). This way we defer reading the state to the Layout phase.</p><pre>@Composable <br>fun Example() {<br>    var state by remember { mutableStateOf(0) }<br><br>    Text(<br>        // Reading the state in Composition phase<br>        &quot;My state = $state&quot;,<br>        Modifier<br>            .layout { measurable, constraints -&gt;<br>                // Reading the state in Layout phase<br>                val size = IntSize(state, state)<br>            }<br>            .drawWithCache {<br>                // Reading the state in Drawing phase<br>                val color = state<br>            }<br>    )<br>}</pre><h4>Reducing the recomposition area</h4><p>You should break into small functions where you can keep parts of the code from recomposition. If you see that part of a function remains unchanged and part of it changes quite often, it is probably better to split this function into two. That way, one function will be skipped and the one that changes frequently will recompose a smaller area. But you should not get carried away and move Divider into a separate function.</p><p>Here is an example of moving the timer logic into a separate function and reducing the number of recompositions in Promo, since only Timer will be restarted (pay attention to the place where timer.value is called, which causes the restart on change):</p><pre>@Composable<br>fun Promo(timer: State&lt;Int&gt;) {<br>    Text(&quot;Sample text&quot;)<br>    Image()<br><br>    // Old timer code right in the Promo function<br>    // Text(&quot;${timer.value} seconds left&quot;)<br><br>    // New timer code<br>    Timer(timer)<br>}<br><br>@Composable<br>fun Timer(timer: State&lt;Int&gt;) {<br>    // Timer code and reading the timer state (timer.value) inside<br>}</pre><h4>Using key and contentType in lists</h4><p>In lazy lists, you need to pass a key to item() so that lists know how the data changes. Also pass <a href="https://developer.android.com/jetpack/compose/lists#content-type">contentType</a> so that lists know which items can be reused.</p><pre>LazyColumn {<br>    items(<br>        items = messages,<br>        key = { message -&gt; message.id },<br>        contentType = { it.type }<br>    ) { message -&gt;<br>        MessageRow(message)<br>    }<br>}</pre><p>If you make a list via forEach, you can use key() {}, then when the list changes, Compose will understand where the elements have moved to.</p><pre>Column {<br>    widgets.forEach { widget -&gt;<br>        key(widget.id) {<br>            MyWidget(widget)<br>        }<br>    }<br>}</pre><h4>Modifiers</h4><h4>Custom modifiers</h4><p>If you write your modifier then:</p><ul><li>If it’s stateless, just use functions.</li><li>If it’s stateful, use Modifier.Node (ModifierNodeElement). Previously, it was recommended to use composed for this. In general, you can do it now, since there is no detailed guide on Modifier.Node yet, only samples (<a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/ModifierSamples.kt">samples 1</a>, <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/ModifierCompositionLocalSample.kt">samples 2</a>).</li><li>If a composable function is called in the modifier, use Modifier.composed.</li></ul><p>Learn more about modifiers in <a href="https://youtu.be/BjGX2RftXsU">this video</a>.</p><h4>Reusing modifiers</h4><p>If there is frequent recomposition in the area where modifiers are created, it is worth considering moving the creation of modifiers outside of this area. This, for example, is relevant for animations:</p><pre>val reusableModifier = Modifier<br>            .padding(12.dp)<br>            .background(Color.Gray),<br><br>@Composable <br>fun LoadingWheelAnimation() { <br>    val animatedState = animateFloatAsState(...) <br><br>    LoadingWheel( <br>        modifier = reusableModifier, <br>        // Reading a frequently changing state<br>        animatedState = animatedState.value<br>    ) <br>}</pre><p>It is also recommended to extract modifiers from lists so that all their elements reuse a single object.</p><pre>val reusableItemModifier = Modifier<br>            .padding(bottom = 12.dp)<br>            .size(216.dp)<br>            .clip(CircleShape) <br><br>@Composable <br>private fun AuthorList(authors: List) { <br>    LazyColumn { <br>        items(authors) { <br>            AsyncImage(modifier = reusableItemModifier) <br>        } <br>    } <br>}</pre><p>You can extract modifiers not only from functions, but also simply to the parent composable function, in which recomposition occurs less often. Further modifiers can be safely appended.</p><pre>reusableModifier.clickable { /*...*/ }<br>otherModifier.then(reusableModifier)</pre><h3>Long calculations during recomposition</h3><h4>Long calculations only in ViewModel or in remember</h4><p>Almost all calculations should be performed only in ViewModel. In this case, make sure that callbacks (onButtonClick, onIntent, onAction, onEvent, onMessage…) do not do heavy work in the main thread. If you have a single function executing in the main thread to process user actions, then you can attach a measurement of the duration of work to it and log critical values of execution time, so that the developer doesn’t forget to move complex and long calculations to background threads.</p><p>It is better to remove all logic from composable functions. In other cases, when it is inconvenient to put long or costly calculations into ViewModel, use remember.</p><h4>Without long calculations in the UI State getters</h4><pre>data class MyUiState(<br>    val list1: List&lt;Int&gt; = emptyList(),<br>    val list2: List&lt;Int&gt; = emptyList(),<br>) {<br>    // Don&#39;t do<br>    val isTextVisible <br>        get() = list1.any { it == 1 } || list2.any { it != 0 }<br>}</pre><p>If you have something like this in UiState so as not to set the field every time, then the recalculation will happen at every recomposition, since it’s just executing the getIsTextVisible() method. So either remove the getter (by leaving the field in the class body or moving it to the primary constructor), or make sure that there is a minimum of recompositions at the place where the getter is called.</p><h4>When to use remember</h4><p>Use:</p><ul><li>For any long or memory-consuming operations that can be executed more than once but should not be executed before changing the keys (if needed) passed to remember(), especially for frequent recomposition.</li></ul><pre>val brush = remember(key1 = avatarRes) {<br>    ShaderBrush(<br>        BitmapShader(<br>            ImageBitmap.imageResource(res, avatarRes).asAndroidBitmap(),<br>            Shader.TileMode.REPEAT,<br>            Shader.TileMode.REPEAT<br>        )<br>    )<br>}</pre><ul><li>For wrapping lambdas with unstable external variables.</li><li>For classes without overridden equals.</li><li>For objects that need to be preserved between recompositions (e.g. State&lt;T&gt;).</li></ul><p>If the remember keys are updated very often, it is worth considering whether remember is needed in this case. Also, you should not add to the keys anything that the calculation inside remember depends on: if you realize that these values will never change during the lifetime of the composable function and remember itself, then don’t add them to the keys.</p><h3>Layout</h3><h4>Custom Layouts</h4><p>Don’t be afraid to make custom layouts: they are much easier than in View, the main thing is to start. Useful videos and articles on this topic in Compose: <a href="https://www.youtube.com/playlist?list=PLWz5rJ2EKKc94tpHND8pW8Qt8ZfT1a4cq">link1</a>, <a href="https://www.youtube.com/watch?v=xcfEQO0k_gU">link2</a>, <a href="https://www.droidcon.com/2022/11/16/thinking-outside-the-box-custom-compose-layouts/">link3</a>, <a href="https://medium.com/androiddevelopers/problem-solving-in-compose-text-d1dd1feafe4a">link4</a>.</p><h4>Unreasonable change in size and position</h4><p>Avoid unreasonable resizing of Compose elements, especially in lists. Such a problem can occur if you don’t set a fixed size for the image and it changes its size after downloading it from the Internet. Unreasonable resizing or positioning can occur due to modifiers onGloballyPositioned(), onSizeChanged() and similar. A lot of unnecessary recomposition can occur because of this. If elements need to know about the position and size of other elements, more often than not it means you are either using the wrong layout or you need to make a custom one.</p><h4>Layout pre-calculation</h4><h4>SubcomposeLayout</h4><p>SubcomposeLayout defers composition until Measurement in the Layout phase so that we can use the available space to compose child elements. A second useful application is conditional composition. For example, depending on the size of the application window, we can arrange elements differently (for a tablet or for a phone, or in general for a window that can be resized). Or depending on the scrolling state, call composition of specific elements to implement a lazy list. SubcomposeLayout is quite expensive, so you shouldn’t use it to precompute the layout in any other case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hVuTI6zKQBF5MqnO" /><figcaption>Subcomposition in the Jetpack Compose lifecycle. <a href="https://medium.com/androiddevelopers/advanced-layout-concepts-eb08cf2a3c8">Source</a></figcaption></figure><p>The main implementations of SubcomposeLayout — BoxWithConstraint, LazyRow and LazyColumn — cover most of the needs that Layout cannot.</p><p>Also, using SubcomposeLayout under the hood explains why LazyRow and LazyColumn lose out to Row and Column in performance with a small number of items. So if you have a small list, use Row and Column for it.</p><p>SubcomposeLayout is sometimes mistakenly used to implement the Slot API:</p><pre>// Don&#39;t do!<br>@Composable<br>fun DontDoThis(<br>    slot1: @Composable () -&gt; Unit,<br>    slot2: @Composable () -&gt; Unit<br>) {<br>    SubcomposeLayout { constraints -&gt;<br>        val slot1Measurables = subcompose(&quot;slot1&quot;, slot1)<br>        val slot2Measurable = subcompose(&quot;slot2&quot;, slot2)<br><br>        layout(width, height) {<br>            ...<br>        }<br>    }<br>}</pre><p>For Slot API there is a more correct option: via the layoutId() modifier and search among measurables by layoutId field or Layout with passing the list of composable and deconstructing the list of measurables in order.</p><pre>@Composable<br>fun DoThis(<br>    slot1: @Composable () -&gt; Unit,<br>    slot2: @Composable () -&gt; Unit<br>) {<br>    Layout(<br>        contents = listOf(slot1, slot2)<br>    ) { (slot1Measurables, slot2Measurables), constraints -&gt;<br>        ...<br>        layout(width, height) {<br>            ...<br>        }<br>    }<br>}</pre><h4>Intrinsic measurements</h4><p>Intrinsic measurements are more efficient than SubcomposeLayout, and under the hood work very similarly to LookaheadLayout. Both approaches invoke the measurement lambda (which is passed in LayoutModifiers or MeasurePolicy) with different constraints in the same frame. But in the case of Intrinsics it is a pre-calculation in order to perform the actual measurement using the obtained values.</p><p>Imagine a Row with three children. In order for its height to match the height of the tallest child, the Row needs to get the intrinsic measurements of all its children and then measure itself using the maximum value. Read more at <a href="https://developer.android.com/jetpack/compose/layouts/intrinsic-measurements">Android Developers</a>.</p><p>Intrinsic measurements can have a negative effect on complex layouts in lazy lists, but not significantly.</p><h4>LookaheadLayout</h4><p>Used for precise pre-calculation of size and position of any (direct or indirect) child in order to power automatic animations (e.g. transition from one element to another). LookaheadLayout also does a more aggressive caching than intrinsics to avoid looking ahead unless the tree has changed. You can read more in the <a href="https://newsletter.jorgecastillo.dev/p/introducing-lookaheadlayout">article by Jorge Castillo</a>.</p><h3>Other tips</h3><h4>Avoid backwards writes</h4><p>This mistake is more typical for beginners. We call a state change immediately after reading, which causes a recomposition.</p><pre>@Composable<br>fun BadComposable() {<br>    var count by remember { mutableStateOf(0) }<br><br>    // Causes recomposition on click<br>    Button(onClick = { count++ }) {<br>        Text(&quot;Recompose&quot;)<br>    }<br><br>    Text(&quot;$count&quot;)<br>    count++ <br>    // Backwards write, writing to state after it has been read<br>}</pre><h4>MovableContentOf</h4><p>movableContentOf is useful when we want to move our elements to a different location without re-invoking the recomposition or losing the memoized state:</p><pre>val myItems = remember {  <br>    movableContentOf {  <br>        MyItem(1)  <br>        MyItem(2)<br>    }  <br>}<br><br>if (isHorizontal) {  <br>    Row {  <br>        myItems()<br>    }  <br>} else {  <br>    Column {  <br>        myItems()  <br>    }  <br>}</pre><p>Read more in the <a href="https://effectiveandroid.substack.com/p/movablecontentof-and-movablecontentwithreceivero">article by Jorge Castillo</a>.</p><p>An interesting fact: the key() construct is similar in logic to movableContentOf(), since both approaches use a movable group, which allows you to move Compose code without recomposition.</p><h4>staticCompositionLocalOf and compositionLocalOf</h4><p>staticCompositionLocalOf is usually needed when Composition Local is used by a huge number of composable functions and the value is unlikely to change. Example implementations: LocalContext, LocalLifecycleOwner, LocalDensity, LocalFocusManager, etc.</p><p>compositionLocalOf incurs an overhead in the initial building of the composition tree, since all composable functions that read the current value must be tracked. If the value will change frequently, compositionLocalOf may be a better choice. Example implementations: LocalConfiguration, LocalAlpha, etc.</p><h4>@ReadOnlyComposable</h4><p>If a composable function performs only read operations, you can mark it with the @ReadOnlyComposable annotation. As a result, it will not have a group generated. This will give a small performance boost. The main use case is a function that only needs the @Composable annotation to read CompositionLocal (e.g., reading a color from a theme) and not to call other composable functions. Read more on <a href="https://developer.android.com/reference/kotlin/androidx/compose/runtime/ReadOnlyComposable">Android Developers</a>.</p><h4>Use less ComposeView</h4><p>It’s simple: the less ComposeView you use to bridge with View, the faster Compose will work. Also, the earlier Compose code appears at application startup, the better the further code will work, because Compose will have time to “warm up”.</p><h4>Use the latest version of Compose</h4><p>Compose developers improve performance in almost every version, so don’t forget to update.</p><h4>Baseline Profiles</h4><p>Baseline Profiles are well documented on <a href="https://developer.android.com/topic/performance/baselineprofiles/overview">Android Developers</a>. In general, Google already does this kind of work for us with Cloud Profiles. Baseline Profiles will help if we want to improve our metrics on older Android versions (7–8.1) and at the start of a new release on newer Androids (9+).</p><h3>Debugging and performance monitoring</h3><p>Optimization is good, but it’s always better to test your changes to make sure you’ve actually solved the problem, not added a new one.</p><p>You should check performance almost always in release mode and with R8. Debug mode has a lot of benefits in development, which slows down and distorts the final application code. The R8 compiler also optimizes the code significantly.</p><p>Also, Compose debugging is well written in <a href="https://medium.com/icerock/optimize-or-die-profiling-and-optimization-in-jetpack-compose-a165c8897b3f">this article</a> and described in a <a href="https://www.youtube.com/watch?v=Kp-aiSU8qCU">video from Android Developers</a>.</p><h4>Stability and skippability testing</h4><p>To check the types and composable functions in a project for stability, you need to run metrics generation. How to do it: <a href="https://chris.banes.me/posts/composable-metrics/">Composable metrics</a> and <a href="https://github.com/androidx/androidx/blob/androidx-main/compose/compiler/design/compiler-metrics.md">Interpreting Compose Compiler Metrics</a>.</p><p>The metrics will be located in the path: your_module/build/compose_metrics. Among them, two files are important:</p><ul><li>-classes.txt for type metrics;</li></ul><pre>unstable class WidgetUiState {<br>  unstable val widgets: List&lt;Widget&gt;<br>  stable val showLoader: Boolean<br>  &lt;runtime stability&gt; = Unstable<br>}</pre><ul><li>-composables.txt and .csv for function metrics;</li></ul><pre>restartable scheme(&quot;[androidx.compose.ui.UiComposable]&quot;) fun MyWidgets(<br>  unstable widgets: List&lt;Widget&gt;<br>  stable modifier: Modifier? = @static Companion<br>)</pre><ul><li>-module.json for module statistics.</li></ul><p>There is also a library for displaying metrics in HTML: <a href="https://patilshreyas.github.io/compose-report-to-html/">Compose Compiler Report to HTML</a>.</p><h4>Debugging recomposition</h4><p>To avoid repeating, I advise you watch <a href="https://youtu.be/SWBN0y0lFNY">the video about debugging recomposition</a>. The point is that you turn on recomposition and skipping counting. After that, you do normal actions on your screen. Then look where there are unnecessary recompositions that could have been avoided, or look where recompositions occur, although the data has not changed and a skipping could occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35aNI4e7wA7nDXJ-wy8vQA.png" /><figcaption>Debugging recomposition. <a href="https://developer.android.com/jetpack/compose/tooling/layout-inspector">Source</a></figcaption></figure><p>You can also use <a href="https://github.com/theapache64/rebugger">Rebugger</a> to debug recompositions. This library allows you to track changes in the given arguments and output the reasons for recomposition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G7SfqG5v-Mc2rCQa" /><figcaption>Rebugger. <a href="https://github.com/theapache64/rebugger">Source</a></figcaption></figure><p>Android Studio Hedgehog <a href="https://developer.android.com/studio/preview/features#compose-state-in-debugger">will add</a> additional information to debuggers to view Compose state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5A9Fgx8o4756OJv3" /><figcaption>Compose state information in debugger. <a href="https://developer.android.com/studio/preview/features#compose-state-in-debugger">Source</a></figcaption></figure><h4>Composition tracing</h4><p>Use composition tracing to deeply analyze the problems of your UI elements. This is described in the <a href="https://developer.android.com/jetpack/compose/performance/tracing">article “Composition tracing”</a> and also a bit in <a href="https://www.youtube.com/watch?v=Kp-aiSU8qCU">this video</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lc5r8xZ6NvQm9Yjz" /><figcaption>Composition tracing. <a href="https://developer.android.com/jetpack/compose/tooling/tracing">Source</a></figcaption></figure><h4>Benchmarking</h4><p>Test your screens after optimizations with <a href="https://github.com/android/performance-samples/tree/main/MacrobenchmarkSample/macrobenchmark/src/main/java/com/example/macrobenchmark">benchmarks</a> (e.g., a <a href="https://github.com/android/performance-samples/blob/main/MacrobenchmarkSample/macrobenchmark/src/main/java/com/example/macrobenchmark/frames/FrameTimingBenchmark.kt">list scrolling benchmark</a> measuring the duration of frame rendering).</p><h3>Summary</h3><p>In this article we described the whole list of optimizations our team encountered and used in practice. Some tips can be converted into your team’s code style and used freely. Others are only useful if your element changes frequently. Check performance after each optimization to avoid degradation. And also it is not necessary to over-optimize your code beforehand, otherwise it will turn into an unreadable thing.</p><h4><a href="https://github.com/tipapro/articles/blob/main/conscious-compose-optimization/en/cheatsheet.md">Cheat sheet</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e16144b80eef" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/conscious-compose-optimization-e16144b80eef">Conscious Compose optimization</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>