Unverified Commit 32b1479a authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Use for...in instead of Object.keys for parallelRouteKey traversal (#89905)

## For Maintainers

### What?

Replace `Object.keys().forEach` with a `for...in` loop in the
`createFlightRouterStateFromLoaderTreeImpl` function.

### Why?

`for...in` avoids the intermediate array allocation from
`Object.keys()`, which becomes increasingly impactful as key count
grows.

| Method | 1 key | 2 keys | 5 keys |
|---|---|---|---|
| `for...in` | **4.5ms** | **6.1ms** | **10.3ms** |
| `for (i) + Object.keys()` | 7.1ms (1.6x) | 17.1ms (2.8x) | 40.1ms
(3.9x) |
| `for...of Object.keys()` | 7.5ms (1.7x) | 17.0ms (2.8x) | 41.3ms
(4.0x) |
| `Object.keys().forEach()` | 10.7ms (2.4x) | 20.0ms (3.3x) | 42.0ms
(4.1x) |

While the impact is minimal this code is in the hot path for rendering
every request so it's worth optimizing. Especially as the payload will
have a lot of single-key cases.

### How?

Changed the `Object.keys(parallelRoutes).forEach()` pattern to a direct
`for (const parallelRouteKey in parallelRoutes)` loop while maintaining
the same functionality.
parent ffdf8fde
......@@ -30,7 +30,7 @@ function createFlightRouterStateFromLoaderTreeImpl(
let childHasLoadingBoundary = false
const children: FlightRouterState[1] = {}
Object.keys(parallelRoutes).forEach((parallelRouteKey) => {
for (const parallelRouteKey in parallelRoutes) {
const child = createFlightRouterStateFromLoaderTreeImpl(
parallelRoutes[parallelRouteKey],
getDynamicParamFromSegment,
......@@ -45,7 +45,7 @@ function createFlightRouterStateFromLoaderTreeImpl(
childHasLoadingBoundary = true
}
children[parallelRouteKey] = child
})
}
segmentTree[1] = children
if (includeHasLoadingBoundary) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment