Unverified Commit 0123a9d5 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Optimize inlined Flight data array format (#52028)

When looking at [some sites](https://rsc-llm-on-the-edge.vercel.app/) with a large amount of chunks streamed, I noticed that the inlined Flight data array can be optimized quite a lot. Currently we do:

```js
self.__next_f.push([1,"d5:[\"4\",[\"$\",\"$a\",null,..."])
```

1. The `self.` isn't needed (except for the initial bootstrap tag) as React itself has `<script>$RC("B:f","S:f")</script>` too.
2. After the bootstrap script tag, all items are an array with `[1, flight_data]` and `flight_data` is always a string. We can just push only these strings.
3. We use `JSON.stringify(flight_payload)` to inline the payload where the payload itself is a string with a lot of double quotes (`"`), this results in a huge amount of backslashes (`\`). Here we can instead replace it to use a pair of single quotes on the outside and un-escape the double quotes inside.

Here's a side-by-side comparison of a small page:

<img width="1710" alt="CleanShot 2023-06-30 at 11 41 02@2x" src="https://github.com/vercel/next.js/assets/3676859/398356ec-91d5-435c-892d-16fb996029e8">

For a real production page I saw the HTML payload reduced by 11,031 bytes, a 3% improvement.

Note that all the tests are not considering gzip here, so the actual traffic impact will be smaller.
parent 0dd225b1
......@@ -41,19 +41,19 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false
let initialServerDataFlushed = false
function nextServerDataCallback(
seg: [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string]
): number {
if (seg[0] === 0) {
type IsBootStrap = 0
type ResponsePartial = string
function nextServerDataCallback(seg: IsBootStrap | ResponsePartial): number {
if (seg === 0) {
initialServerDataBuffer = []
} else {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[1]))
initialServerDataWriter.enqueue(encoder.encode(seg))
} else {
initialServerDataBuffer.push(seg[1])
initialServerDataBuffer.push(seg)
}
}
return 0
......
......@@ -10,10 +10,10 @@ declare global {
var __next_require__: (id: string) => any
var __next_chunk_load__: (id: string) => Promise
var __next_f: (
| [isBootStrap: 0]
| [isNotBootstrap: 1, responsePartial: string]
)[]
type isBootStrap = 0
type responsePartial = string
var __next_f: (isBootStrap | responsePartial)[]
var next: {
version: string
appDir?: boolean
......
......@@ -116,19 +116,19 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false
let initialServerDataFlushed = false
function nextServerDataCallback(
seg: [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string]
): void {
if (seg[0] === 0) {
type IsBootStrap = 0
type ResponsePartial = string
function nextServerDataCallback(seg: IsBootStrap | ResponsePartial): void {
if (seg === 0) {
initialServerDataBuffer = []
} else {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[1]))
initialServerDataWriter.enqueue(encoder.encode(seg))
} else {
initialServerDataBuffer.push(seg[1])
initialServerDataBuffer.push(seg)
}
}
}
......
......@@ -53,7 +53,7 @@ export function useFlightResponse(
writer.write(
encodeText(
`${startScriptTag}(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(
JSON.stringify([0])
JSON.stringify(0)
)})</script>`
)
)
......@@ -63,8 +63,14 @@ export function useFlightResponse(
writer.close()
} else {
const responsePartial = decodeText(value, textDecoder)
const scripts = `${startScriptTag}self.__next_f.push(${htmlEscapeJsonString(
JSON.stringify([1, responsePartial])
const scripts = `${startScriptTag}__next_f.push(${htmlEscapeJsonString(
// Since the inlined payload is always a JSON-ish encoded string with
// many double quotes, we can safely un-escape these quotes and use
// a single quote to wrap the string. This saves a lot of bytes.
JSON.stringify(responsePartial)
.replace(/\\"/g, '"')
.replace(/'/g, "\\'")
.replace(/(^")|("$)/g, "'")
)})</script>`
writer.write(encodeText(scripts))
......
......@@ -15,8 +15,11 @@ createNextDescribe(
})
it('should allow to have a valid /not-found route', async () => {
const html = await next.render('/not-found')
expect(html).toContain("I'm still a valid page")
const browser = await next.browser('/not-found')
await check(
() => browser.elementByCss('h1').text(),
`I'm still a valid page`
)
})
if (isNextDev) {
......
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