Home > Mobile >  Compose Spacer vs view padding performance
Compose Spacer vs view padding performance

Time:12-03

I prefer using a Spacer to add some padding between views, sometimes you could just add this space as padding to the views. So my question is are there any performance drawbacks of using Spacers versus using the good old padding values?

CodePudding user response:

The performance will vary. In the test below, 50 items are rendered with padding followed by 50 items using spacers. The spacers render around twice as fast. But if you reverse the order and render 50 items with spacers first followed by 50 items with padding, the padding is faster with around 0.2 times the duration it takes with spacers. So clearly the number of items and the order in which they are rendered is going to affect the performance significantly. I suspect someone at Google gives you better performance if you like cats more than you like dogs :-)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivity(intent)

        setContent {
            val modifierPadding = Modifier.padding(bottom = 10.dp)
            val modifierSpacer = Modifier
                .requiredHeight(1.dp)
                .fillMaxWidth()

            Column(modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())) {
                val startTimePadding = System.nanoTime()

                repeat(50) {
                    Text("I like dogs", modifier = modifierPadding)
                }

                val durationPadding = System.nanoTime() - startTimePadding
                val startTimeSpacer = System.nanoTime()

                repeat(50) {
                    Text("I like cats")
                    Spacer(modifier = modifierSpacer)
                }

                val durationSpacer = System.nanoTime() - startTimeSpacer

                Text("padding to spacer ratio: "   (durationPadding.toFloat() / durationSpacer.toFloat()))
            }
        }
    }
}
  • Related