perf(ui): меньше аллокаций и рекомпозиций на кадр

Кэш иконок на LruCache с потолком вместо безлимитной мапы, пульс онлайна
через graphicsLayer (без рекомпозиции), общая Matrix в MorphShape,
мемоизация colorScheme/motionScheme и списка nav-итемов.
This commit is contained in:
samosvalishe committed 2026-07-29 15:09:52 +03:00
1 parent 2573d47c1c
commit f99e18c024
5 files changed
+39 -34

No files matched your search

@@ -1,6 +1,7 @@
package com.freeturn.app.ui.components package com.freeturn.app.ui.components
import android.content.Context import android.content.Context
import android.util.LruCache
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
@@ -16,26 +17,22 @@ import androidx.compose.ui.unit.dp
import androidx.core.graphics.drawable.toBitmap import androidx.core.graphics.drawable.toBitmap
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
/**
* Кэш иконок приложений в памяти (packageName -> ImageBitmap). Иконки растеризуются
* до фиксированного размера, чтобы ограничить память; loadIcon тяжёлый - только IO.
*/
private object AppIconCache { private object AppIconCache {
private const val ICON_PX = 160 private const val ICON_PX = 160
private val cache = ConcurrentHashMap<String, ImageBitmap>() private const val MAX_ICONS = 64
private val cache = object : LruCache<String, ImageBitmap>(MAX_ICONS) {}
fun cached(packageName: String): ImageBitmap? = cache[packageName] fun cached(packageName: String): ImageBitmap? = cache.get(packageName)
suspend fun load(context: Context, packageName: String): ImageBitmap? = suspend fun load(context: Context, packageName: String): ImageBitmap? =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
cache[packageName]?.let { return@withContext it } cache.get(packageName)?.let { return@withContext it }
runCatching { runCatching {
context.packageManager.getApplicationIcon(packageName) context.packageManager.getApplicationIcon(packageName)
.toBitmap(ICON_PX, ICON_PX) .toBitmap(ICON_PX, ICON_PX)
.asImageBitmap() .asImageBitmap()
.also { cache[packageName] = it } .also { cache.put(packageName, it) }
}.getOrNull() }.getOrNull()
} }
} }
@@ -26,6 +26,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@@ -112,9 +113,10 @@ fun AppNavigation(
NavigationSuiteScaffold( NavigationSuiteScaffold(
navigationSuiteType = suiteType, navigationSuiteType = suiteType,
navigationItems = { navigationItems = {
val items = if (logsTabVisible) { val items = remember(logsTabVisible) {
navItems.toMutableList().apply { add(1, logsNavItem) } if (logsTabVisible) navItems.toMutableList().apply { add(1, logsNavItem) }
} else navItems else navItems
}
items.forEach { item -> items.forEach { item ->
val selected = destination?.hierarchy?.any { it.hasRoute(item.graphRoute::class) } == true val selected = destination?.hierarchy?.any { it.hasRoute(item.graphRoute::class) } == true
NavigationSuiteItem( NavigationSuiteItem(
@@ -355,19 +355,22 @@ private fun rememberMorphingShape(target: RoundedPolygon, reducedMotion: Boolean
progress.snapTo(0f) progress.snapTo(0f)
progress.animateTo(1f, spec) progress.animateTo(1f, spec)
} }
// Общий буфер пути: MorphShape пересоздаётся каждый кадр морфа, аллокация Path на кадр не нужна.
val buffer = remember { android.graphics.Path() } val buffer = remember { android.graphics.Path() }
return MorphShape(morph, progress.value, buffer) val matrix = remember { Matrix() }
return MorphShape(morph, progress.value, buffer, matrix)
} }
private class MorphShape( private class MorphShape(
private val morph: Morph, private val morph: Morph,
private val progress: Float, private val progress: Float,
private val buffer: android.graphics.Path private val buffer: android.graphics.Path,
// Общая с буфером пути: createOutline зовут каждый кадр морфа.
private val matrix: Matrix
) : Shape { ) : Shape {
override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline { override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline {
val path = morph.toPath(progress.coerceIn(0f, 1f), buffer).asComposePath() val path = morph.toPath(progress.coerceIn(0f, 1f), buffer).asComposePath()
val matrix = Matrix() matrix.reset()
matrix.scale(size.width, size.height) matrix.scale(size.width, size.height)
path.transform(matrix) path.transform(matrix)
return Outline.Generic(path) return Outline.Generic(path)
@@ -25,7 +25,9 @@ import androidx.compose.material3.LoadingIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
@@ -33,7 +35,7 @@ import androidx.compose.runtime.setValue
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -269,15 +271,15 @@ private fun UserRowMenu(
@Composable @Composable
private fun OnlineDot(modifier: Modifier = Modifier) { private fun OnlineDot(modifier: Modifier = Modifier) {
val pulse = if (LocalReducedMotion.current) 1f else { val pulse: State<Float> = if (LocalReducedMotion.current) {
val transition = rememberInfiniteTransition(label = "online") remember { mutableFloatStateOf(1f) }
val a by transition.animateFloat( } else {
rememberInfiniteTransition(label = "online").animateFloat(
initialValue = 1f, initialValue = 1f,
targetValue = 0.3f, targetValue = 0.3f,
animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse), animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
label = "online_alpha" label = "online_alpha"
) )
a
} }
Box( Box(
modifier = modifier modifier = modifier
@@ -288,7 +290,7 @@ private fun OnlineDot(modifier: Modifier = Modifier) {
Box( Box(
modifier = Modifier modifier = Modifier
.size(9.dp) .size(9.dp)
.alpha(pulse) .graphicsLayer { alpha = pulse.value }
.background(MaterialTheme.extendedColorScheme.success, CircleShape) .background(MaterialTheme.extendedColorScheme.success, CircleShape)
) )
} }
@@ -1,8 +1,8 @@
package com.freeturn.app.ui.theme package com.freeturn.app.ui.theme
import android.app.Activity
import android.os.Build import android.os.Build
import android.provider.Settings import android.provider.Settings
import androidx.activity.compose.LocalActivity
import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.MaterialExpressiveTheme import androidx.compose.material3.MaterialExpressiveTheme
@@ -22,9 +22,9 @@ import androidx.core.view.WindowCompat
/** /**
* Системная настройка "Убрать анимации" (Settings -> Спец. возможности). true = анимации * Системная настройка "Убрать анимации" (Settings -> Спец. возможности). true = анимации
* выключены. Читается один раз за жизнь Activity (staticCompositionLocalOf + keyless * выключены. Читается один раз за жизнь Activity - живое переключение тумблера для
* remember) - живое переключение тумблера для приложения избыточно. Потребители гасят * приложения избыточно. Потребители гасят необязательную моушн: nav-переходы,
* необязательную моушн: nav-переходы, animateContentSize и т.п. * animateContentSize и т.п.
*/ */
val LocalReducedMotion = staticCompositionLocalOf { false } val LocalReducedMotion = staticCompositionLocalOf { false }
@@ -112,25 +112,26 @@ fun FreeTurnTheme(
dynamicColor: Boolean = true, dynamicColor: Boolean = true,
content: @Composable () -> Unit content: @Composable () -> Unit
) { ) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current val context = LocalContext.current
val colorScheme = remember(context, darkTheme, dynamicColor) {
when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> darkScheme darkTheme -> darkScheme
else -> lightScheme else -> lightScheme
} }
}
val motionScheme = remember { MotionScheme.expressive() }
val view = LocalView.current val view = LocalView.current
if (!view.isInEditMode) { val window = LocalActivity.current?.window
if (window != null) {
SideEffect { SideEffect {
val window = (view.context as Activity).window
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
} }
} }
val context = LocalContext.current val reduceMotion = remember(context) {
val reduceMotion = remember {
Settings.Global.getFloat( Settings.Global.getFloat(
context.contentResolver, context.contentResolver,
Settings.Global.ANIMATOR_DURATION_SCALE, Settings.Global.ANIMATOR_DURATION_SCALE,
@@ -144,7 +145,7 @@ fun FreeTurnTheme(
) { ) {
MaterialExpressiveTheme( MaterialExpressiveTheme(
colorScheme = colorScheme, colorScheme = colorScheme,
motionScheme = MotionScheme.expressive(), motionScheme = motionScheme,
typography = Typography, typography = Typography,
shapes = AppShapes, shapes = AppShapes,
content = content content = content