Javad Vatan
Javad Vatan

Reputation: 93

Why doesn't dimensionResource in Jetpack Compose use remember, and what happens if we add it?

In Jetpack Compose, we use dimensionResource to retrieve a dimension value from resources and convert it to Dp. The built-in function is defined as:

@Composable
@ReadOnlyComposable
fun dimensionResource(@DimenRes id: Int): Dp {
    val context = LocalContext.current
    val density = LocalDensity.current
    val pxValue = context.resources.getDimension(id)
    return Dp(pxValue / density.density)
}

This function does not use remember.

My questions:

  1. Why does not dimensionResource internally use remember to cache the result and prevent redundant recomputation during recomposition?

  2. What would happen if I wrapped it in remember like this?

    @Composable
    fun rememberedDimensionResource(@DimenRes id: Int): Dp {
        val context = LocalContext.current
        val density = LocalDensity.current
        return remember(id) {
            val pxValue = context.resources.getDimension(id)
            Dp(pxValue / density.density)
        }
    }
    

    Would this improve performance by avoiding unnecessary resource lookups, or is there a reason why dimensionResource is designed without remember?

I'm trying to understand the implications of caching dimension values in Jetpack Compose and whether this would provide a real optimization.

Upvotes: 2

Views: 51

Answers (1)

tyg
tyg

Reputation: 15773

dimensionResource is a composable function, and composables are generally only executed again when their parameters (or a MutableState they access) are changed. When you do not dynamically change the id parameter the execution of dimensionResource is skipped on recomposition, preventing unnecessary execution of the same code over and over again.

To answer the specific questions:

  1. remember is not used internally because it is not needed. It would even violate the guarantee given by the @ReadOnlyComposable annotation which requires only read operations on the composer, because remember internally calls the composer's updateRememberedValue.
  2. Adding remember would not change the recomposition behavior, but it would incur a (small) performance penalty, unnecessarily invoking the remember mechanism.

Upvotes: 1

Related Questions