Skip to content

Commit

Permalink
Add simple cache to keep RouteBuilder instances, to prevent memory le…
Browse files Browse the repository at this point in the history
…aks and performance degradation after large number of recompositions
  • Loading branch information
rjaros committed Oct 19, 2024
1 parent f13119e commit 016604d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ public class RouteBuilder internal constructor(private val basePath: String, pri
val currentRouter = Router.current
val delegatingRouter = remember(newPath) { DelegateRouter(basePath, currentRouter) }
CompositionLocalProvider(RouterCompositionLocal provides delegatingRouter) {
val newState = RouteBuilder(basePath, newPath)
val newState = routeBuilderCache.getOrPut("${currentRouter.hashCode()} $basePath $newPath") {
RouteBuilder(basePath, newPath)
}
newState.nestedRoute()
}
}
Expand Down Expand Up @@ -167,4 +169,12 @@ public class RouteBuilder internal constructor(private val basePath: String, pri
}
}
}

public companion object {
/**
* Cache for [RouteBuilder] to prevent memory leaks and
* performance degradation after large number of recompositions.
*/
internal var routeBuilderCache = mutableMapOf<String, RouteBuilder>()
}
}
6 changes: 5 additions & 1 deletion src/commonMain/kotlin/app/softwork/routingcompose/Router.kt
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ public fun Router.route(
CompositionLocalProvider(RouterCompositionLocal provides this) {
val rawPath by getPath(initRoute)
val path = Path.from(rawPath)
val node = remember(path) { RouteBuilder(path.path, path) }
val node = remember(path) {
RouteBuilder.routeBuilderCache.getOrPut("${this.hashCode()} ${path.path} $path") {
RouteBuilder(path.path, path)
}
}
node.routing()
}
}
Expand Down

0 comments on commit 016604d

Please sign in to comment.