Commit fa327485 authored by Tim Neutkens's avatar Tim Neutkens

Update bench

parent 1b05c557
......@@ -134,8 +134,8 @@ function createFromJSONCallback_A(response) {
(initializingHandler_A = value.parent),
value.errored)
)
(key = new ReactPromise('rejected', null, value.reason)),
(key = createLazyChunkWrapper(key))
((key = new ReactPromise('rejected', null, value.reason)),
(key = createLazyChunkWrapper(key)))
else if (0 < value.deps) {
var blockedChunk = new ReactPromise('blocked', null, null)
value.value = key
......@@ -279,10 +279,7 @@ function createFromJSONCallback_C(response) {
createLazyChunkWrapper(response)
)
case 64:
return (
(key = parseInt(value.slice(2), 16)),
getChunk(response, key)
)
return ((key = parseInt(value.slice(2), 16)), getChunk(response, key))
case 83:
return Symbol.for(value.slice(2))
case 73:
......@@ -375,13 +372,7 @@ function postProcessWalk(response, obj) {
case 110:
return BigInt(obj.slice(2))
default:
return getOutlinedModel(
response,
obj.slice(1),
null,
'',
createModel
)
return getOutlinedModel(response, obj.slice(1), null, '', createModel)
}
}
if (typeof obj !== 'object' || obj === null) return obj
......@@ -469,13 +460,7 @@ function reviverFn_F(key, value) {
default:
return (
(value = value.slice(1)),
getOutlinedModel(
currentResponse_F,
value,
this,
key,
createModel
)
getOutlinedModel(currentResponse_F, value, this, key, createModel)
)
}
}
......@@ -752,21 +737,30 @@ function runSuite(payloadName, payload, iterations) {
name: 'A: Original (prod)',
fn: () => {
initializingHandler_A = null
return JSON.parse(payload, createFromJSONCallback_A(createMockResponse()))
return JSON.parse(
payload,
createFromJSONCallback_A(createMockResponse())
)
},
},
{
name: 'B: charCodeAt+earlyRet',
fn: () => {
initializingHandler_B = null
return JSON.parse(payload, createFromJSONCallback_B(createMockResponse()))
return JSON.parse(
payload,
createFromJSONCallback_B(createMockResponse())
)
},
},
{
name: 'C: Fully inlined',
fn: () => {
initializingHandler_C = null
return JSON.parse(payload, createFromJSONCallback_C(createMockResponse()))
return JSON.parse(
payload,
createFromJSONCallback_C(createMockResponse())
)
},
},
{
......@@ -818,8 +812,7 @@ function runSuite(payloadName, payload, iterations) {
// Show reviver overhead vs bare JSON.parse
const baseline = results[results.length - 1]
const origOverhead =
((results[0].avg - baseline.avg) / baseline.avg) * 100
const origOverhead = ((results[0].avg - baseline.avg) / baseline.avg) * 100
console.log(
`\n Reviver overhead vs bare JSON.parse: +${origOverhead.toFixed(1)}%`
)
......@@ -837,13 +830,22 @@ function runParseModelStringMicro() {
const parentObj = {}
const plainStrings = [
'div', 'span', 'p', 'h1', 'h2', 'a', 'button',
'div',
'span',
'p',
'h1',
'h2',
'a',
'button',
'text-sm font-medium leading-6 text-gray-900',
'flex items-center justify-between gap-x-6 py-5',
'mx-auto max-w-2xl text-center',
'Hello World',
'Some longer text content that appears in a paragraph',
'/api/data', '/getting-started', 'container', 'main-content',
'/api/data',
'/getting-started',
'container',
'main-content',
'inline-flex items-center rounded-md bg-green-50 px-2 py-1',
'border-b border-gray-200 py-4',
'text-4xl font-bold tracking-tight text-gray-900 sm:text-6xl',
......@@ -851,7 +853,8 @@ function runParseModelStringMicro() {
]
const testValues = []
for (let i = 0; i < 600; i++) testValues.push(plainStrings[i % plainStrings.length])
for (let i = 0; i < 600; i++)
testValues.push(plainStrings[i % plainStrings.length])
for (let i = 0; i < 150; i++) testValues.push('$')
for (let i = 0; i < 200; i++) testValues.push('$' + (i % 64).toString(16))
for (let i = 0; i < 50; i++)
......@@ -876,14 +879,16 @@ function runParseModelStringMicro() {
for (const { name, fn } of parsers) {
// Warmup
for (let w = 0; w < 500; w++) {
for (let i = 0; i < testValues.length; i++) fn(response, parentObj, '0', testValues[i])
for (let i = 0; i < testValues.length; i++)
fn(response, parentObj, '0', testValues[i])
}
if (global.gc) global.gc()
const times = []
for (let b = 0; b < iterations; b++) {
const start = performance.now()
for (let i = 0; i < testValues.length; i++) fn(response, parentObj, '0', testValues[i])
for (let i = 0; i < testValues.length; i++)
fn(response, parentObj, '0', testValues[i])
times.push(performance.now() - start)
}
times.sort((a, b) => a - b)
......@@ -895,14 +900,17 @@ function runParseModelStringMicro() {
})
}
console.log(` ${testValues.length} calls per iteration, ${iterations} iterations\n`)
console.log(
` ${testValues.length} calls per iteration, ${iterations} iterations\n`
)
console.log(
` ${'Variant'.padEnd(20)} ${'Avg (ms)'.padStart(10)} ${'P50 (ms)'.padStart(10)} ${'Min (ms)'.padStart(10)} ${'vs Orig'.padStart(9)}`
)
console.log(` ${'-'.repeat(59)}`)
for (const r of allResults) {
const sp = ((allResults[0].avg - r.avg) / allResults[0].avg) * 100
const spStr = r === allResults[0] ? ' -' : `${sp > 0 ? '+' : ''}${sp.toFixed(1)}%`
const spStr =
r === allResults[0] ? ' -' : `${sp > 0 ? '+' : ''}${sp.toFixed(1)}%`
console.log(
` ${r.name.padEnd(20)} ${r.avg.toFixed(4).padStart(10)} ${r.p50.toFixed(4).padStart(10)} ${r.min.toFixed(4).padStart(10)} ${spStr.padStart(9)}`
)
......
......@@ -4,53 +4,19 @@
// Tests the actual production code path through initializeModelChunk.
//
// Run: node --expose-gc bench-rsc-walk.js
//
// This benchmark uses require() (not vm.createContext) so both versions
// run in the same V8 context — matching real-world conditions.
const { performance } = require('perf_hooks')
const fs = require('fs')
const path = require('path')
const BASE =
'packages/next/dist/compiled/react-server-dom-turbopack/cjs'
const MODIFIED_FILE = path.join(BASE, 'react-server-dom-turbopack-client.node.production.js')
const BACKUP_FILE = path.join(BASE, 'react-server-dom-turbopack-client.node.production.js.bak')
// We can't require both files directly since they'd cache. Instead, we extract
// the key functions using a sandboxed require via vm module.
const vm = require('vm')
function loadModule(filePath) {
const code = fs.readFileSync(filePath, 'utf8')
const mod = { exports: {} }
const sandbox = {
module: mod,
exports: mod.exports,
require: require,
console: console,
Error: Error,
Symbol: Symbol,
Promise: Promise,
Object: Object,
Array: Array,
Map: Map,
Set: Set,
Uint8Array: Uint8Array,
ArrayBuffer: ArrayBuffer,
DataView: DataView,
BigInt: BigInt,
parseInt: parseInt,
parseFloat: parseFloat,
Infinity: Infinity,
NaN: NaN,
isNaN: isNaN,
TextDecoder: require('util').TextDecoder,
global: {},
setTimeout: setTimeout,
queueMicrotask: queueMicrotask,
}
vm.createContext(sandbox)
vm.runInContext(code, sandbox, { filename: filePath })
return mod.exports
}
const BASE = 'packages/next/dist/compiled/react-server-dom-turbopack/cjs'
const MODIFIED_FILE = path.resolve(
BASE,
'react-server-dom-turbopack-client.node.production.js'
)
// ─── Generate realistic RSC payloads ────────────────────────────────────────
// These match what the server produces: each row is a JSON string that gets
......@@ -77,9 +43,7 @@ function makeSmallPayload() {
}
function makeMediumPayload() {
// A page with nav + content
const navItems = ['Product', 'Features', 'Pricing', 'About'].map(
(name) => [
const navItems = ['Product', 'Features', 'Pricing', 'About'].map((name) => [
'$',
'a',
null,
......@@ -88,8 +52,7 @@ function makeMediumPayload() {
className: 'text-sm font-semibold leading-6 text-gray-900',
children: name,
},
]
)
])
return makeElementRow('main', {
className: 'min-h-screen bg-white',
children: [
......@@ -128,7 +91,6 @@ function makeMediumPayload() {
}
function makeLargePayload() {
// 30-item list (common pattern: tables, feeds)
const items = Array.from({ length: 30 }, (_, i) => [
'$',
'div',
......@@ -174,7 +136,8 @@ function makeLargePayload() {
{
className:
'inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700',
children: i % 3 === 0 ? 'Active' : i % 3 === 1 ? 'Pending' : 'Inactive',
children:
i % 3 === 0 ? 'Active' : i % 3 === 1 ? 'Pending' : 'Inactive',
},
],
],
......@@ -187,7 +150,6 @@ function makeLargePayload() {
}
function makeXLPayload() {
// Nested tree: simulates a complex dashboard
function makeCard(i) {
return [
'$',
......@@ -227,7 +189,7 @@ function makeXLPayload() {
null,
{
className: 'text-2xl font-bold',
children: '' + (i * 1234),
children: '' + i * 1234,
},
],
[
......@@ -284,6 +246,23 @@ function makeXLPayload() {
})
}
function makeTablePayload(rowCount) {
const rows = Array.from({ length: rowCount }, (_, i) => [
'$',
'tr',
'row-' + i,
{
children: [
['$', 'td', null, { children: '' + i }],
['$', 'td', null, { children: 'Item ' + i }],
],
},
])
return makeElementRow('table', {
children: ['$', 'tbody', null, { children: rows }],
})
}
// ─── Benchmark infrastructure ───────────────────────────────────────────────
const REACT_ELEMENT_TYPE = Symbol.for('react.transitional.element')
......@@ -299,126 +278,15 @@ function countElements(obj) {
return count
}
// Simulate what the RSC runtime does: create a response, resolve a chunk,
// then initialize it (which triggers JSON.parse + reviver/walk).
function createTestHarness(moduleExports) {
return function parsePayload(jsonString) {
// Create a minimal response using the module's exported createFromFetch
// infrastructure. We'll simulate the chunk resolution directly.
//
// The module doesn't export initializeModelChunk directly, but we can
// simulate the pipeline by creating a stream and feeding data.
// We'll use a simpler approach: create a response and manually trigger
// the parsing path via the public API.
return null // placeholder - we'll use a different approach
}
}
// ─── Load module via require() for same V8 context ──────────────────────────
// We patch the file to export internals, save as temp file, and require() it.
// This ensures both versions run in the same V8 context — no vm overhead.
// Since the modules don't expose initializeModelChunk directly, we need a
// different approach. We'll extract and benchmark the core functions.
// The most accurate way: use the module's createFromReadableStream and feed
// it real RSC wire-format data.
function makeRSCStream(payloads) {
// RSC wire format: each row is "ID:TYPE_TAG:JSON\n" or "ID:JSON\n"
// For model rows (type 0, the default), format is just "ID:JSON\n"
const encoder = new TextEncoder()
const chunks = payloads.map((json, i) => {
// Row format: hex(id) ":" json "\n"
return encoder.encode(i.toString(16) + ':' + json + '\n')
})
let chunkIndex = 0
return new ReadableStream({
pull(controller) {
if (chunkIndex < chunks.length) {
controller.enqueue(chunks[chunkIndex++])
} else {
controller.close()
}
},
})
}
async function benchmarkModule(label, modulePath, payloads, iterations) {
// Clear require cache to get fresh module
delete require.cache[require.resolve(modulePath)]
const mod = require(modulePath)
// Warmup: parse all payloads a few times
for (let w = 0; w < Math.min(100, iterations); w++) {
for (const json of payloads) {
const stream = makeRSCStream([json])
const result = mod.createFromReadableStream(stream, {
serverConsumerManifest: {
moduleMap: null,
serverModuleMap: null,
moduleLoading: null,
},
})
try {
await result
} catch (e) {
// Chunks might not fully resolve in this simplified setup.
// That's OK — we're measuring the parse path.
}
// Small delay to let the stream complete
await new Promise((r) => setTimeout(r, 0))
}
}
if (global.gc) global.gc()
const times = []
for (let i = 0; i < iterations; i++) {
const start = performance.now()
for (const json of payloads) {
const stream = makeRSCStream([json])
const result = mod.createFromReadableStream(stream, {
serverConsumerManifest: {
moduleMap: null,
serverModuleMap: null,
moduleLoading: null,
},
})
// Don't await - we just want to measure the sync parse path
// The stream reading + initializeModelChunk is what we're measuring
}
// Let microtasks flush (stream reading is async)
await new Promise((r) => setTimeout(r, 0))
times.push(performance.now() - start)
}
times.sort((a, b) => a - b)
return {
label,
avg: times.reduce((a, b) => a + b, 0) / times.length,
p50: times[Math.floor(times.length * 0.5)],
p95: times[Math.floor(times.length * 0.95)],
min: times[0],
}
}
// ─── Alternative: direct function extraction benchmark ──────────────────────
// More accurate — extracts the core functions and benchmarks them directly
// without stream overhead.
function extractCoreFunctions(filePath) {
function loadWithInternalsExposed(filePath, tempSuffix) {
const code = fs.readFileSync(filePath, 'utf8')
// We need to extract initializeModelChunk and its dependencies.
// The cleanest way: eval the module in a sandbox and expose internals.
const mod = { exports: {} }
const util = require('util')
// Patch the code to expose internals we need for benchmarking
const patchedCode =
code +
`
const patch = `
;(function() {
// Expose internals for benchmarking
module.exports.__benchmark = {
ResponseInstance: ResponseInstance,
initializeModelChunk: initializeModelChunk,
......@@ -427,85 +295,44 @@ function extractCoreFunctions(filePath) {
};
})();
`
const dir = path.dirname(filePath)
const ext = path.extname(filePath)
const base = path.basename(filePath, ext)
const tempPath = path.join(dir, base + tempSuffix + ext)
fs.writeFileSync(tempPath, code + patch)
const script = new vm.Script(patchedCode, { filename: filePath })
const context = vm.createContext({
module: mod,
exports: mod.exports,
require: require,
console: console,
global: {},
process: { env: {} },
Error: Error,
TypeError: TypeError,
RangeError: RangeError,
Symbol: Symbol,
Promise: Promise,
Object: Object,
Array: Array,
Map: Map,
Set: Set,
WeakMap: WeakMap,
WeakRef: WeakRef,
FinalizationRegistry: FinalizationRegistry,
Uint8Array: Uint8Array,
ArrayBuffer: ArrayBuffer,
DataView: DataView,
BigInt: BigInt,
parseInt: parseInt,
parseFloat: parseFloat,
Infinity: Infinity,
NaN: NaN,
isNaN: isNaN,
setTimeout: setTimeout,
clearTimeout: clearTimeout,
queueMicrotask: queueMicrotask,
TextDecoder: util.TextDecoder,
ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
Headers: typeof Headers !== 'undefined' ? Headers : undefined,
Blob: typeof Blob !== 'undefined' ? Blob : undefined,
FormData: typeof FormData !== 'undefined' ? FormData : undefined,
Date: Date,
RegExp: RegExp,
JSON: JSON,
Math: Math,
String: String,
Number: Number,
Boolean: Boolean,
Proxy: Proxy,
Reflect: Reflect,
encodeURIComponent: encodeURIComponent,
decodeURIComponent: decodeURIComponent,
})
script.runInContext(context)
return mod.exports.__benchmark
try {
// Clear cache in case of re-runs
delete require.cache[require.resolve(tempPath)]
const mod = require(tempPath)
return mod.__benchmark
} finally {
// Clean up temp file
try {
fs.unlinkSync(tempPath)
} catch (e) {}
}
}
// ─── Direct benchmark ───────────────────────────────────────────────────────
function directBenchmark(label, internals, payloads, iterations) {
const { ResponseInstance, initializeModelChunk, ReactPromise, getChunk } = internals
const { ResponseInstance, initializeModelChunk, ReactPromise } = internals
// Create a response instance
function makeResponse() {
return new ResponseInstance(
null, // bundlerConfig
null, // serverReferenceConfig
null, // moduleLoading
undefined, // callServer
undefined, // encodeFormAction
undefined, // nonce
undefined // temporaryReferences
null,
null,
null,
undefined,
undefined,
undefined,
undefined
)
}
// Simulate how initializeModelChunk is called:
// 1. A chunk is created with status "resolved_model"
// 2. chunk.value = JSON string, chunk.reason = response
// 3. initializeModelChunk(chunk) is called
function createResolvedModelChunk(response, json) {
const chunk = new ReactPromise('resolved_model', json, response)
return chunk
return new ReactPromise('resolved_model', json, response)
}
// Correctness check
......@@ -525,7 +352,7 @@ function directBenchmark(label, internals, payloads, iterations) {
}
if (global.gc) global.gc()
// Measure
// Measure in batches
const times = []
const batchSize = 100
const batches = Math.ceil(iterations / batchSize)
......@@ -556,7 +383,7 @@ function directBenchmark(label, internals, payloads, iterations) {
// ─── Main ───────────────────────────────────────────────────────────────────
async function main() {
function main() {
console.log('React Server DOM — reviver vs walk benchmark')
console.log(`Node.js ${process.version}`)
console.log(`Date: ${new Date().toISOString()}`)
......@@ -564,17 +391,48 @@ async function main() {
`GC exposed: ${typeof global.gc === 'function' ? 'yes' : 'no (use --expose-gc)'}`
)
console.log('\nLoading modules...')
const origInternals = extractCoreFunctions(path.resolve(BACKUP_FILE))
const walkInternals = extractCoreFunctions(path.resolve(MODIFIED_FILE))
const BACKUP_FILE = path.resolve(
BASE,
'react-server-dom-turbopack-client.node.production.js.bak'
)
if (!fs.existsSync(BACKUP_FILE)) {
console.error(
`\nERROR: Backup file not found: ${BACKUP_FILE}\n` +
`Create it with the original (unmodified) version:\n` +
` git show HEAD~2:packages/next/src/compiled/react-server-dom-turbopack/cjs/react-server-dom-turbopack-client.node.production.js > ${BACKUP_FILE}`
)
process.exit(1)
}
console.log('\nLoading modules via require() (same V8 context)...')
const origInternals = loadWithInternalsExposed(BACKUP_FILE, '.orig-bench')
const walkInternals = loadWithInternalsExposed(MODIFIED_FILE, '.walk-bench')
console.log(' Original (reviver): loaded')
console.log(' Modified (walk): loaded')
const suites = [
{ name: 'Small (2 elements)', payloads: [makeSmallPayload()], iters: 50000 },
{ name: 'Medium (~12 elements)', payloads: [makeMediumPayload()], iters: 20000 },
{ name: 'Large (~90 elements)', payloads: [makeLargePayload()], iters: 5000 },
{
name: 'Small (2 elements)',
payloads: [makeSmallPayload()],
iters: 50000,
},
{
name: 'Medium (~12 elements)',
payloads: [makeMediumPayload()],
iters: 20000,
},
{
name: 'Large (~90 elements)',
payloads: [makeLargePayload()],
iters: 5000,
},
{ name: 'XL (~200 elements)', payloads: [makeXLPayload()], iters: 2000 },
{
name: 'Table (1000 rows)',
payloads: [makeTablePayload(1000)],
iters: 500,
},
]
for (const suite of suites) {
......@@ -623,7 +481,4 @@ async function main() {
console.log(`${'═'.repeat(82)}`)
}
main().catch((e) => {
console.error(e)
process.exit(1)
})
main()
......@@ -186,7 +186,13 @@ function runBench(label, internals, jsonPayload, iterations) {
function makeResponse() {
return new ResponseInstance(
null, null, null, undefined, undefined, undefined, undefined
null,
null,
null,
undefined,
undefined,
undefined,
undefined
)
}
......@@ -265,7 +271,9 @@ function printResults(suite, results) {
console.log('<Table> RSC payload benchmark — reviver vs walk')
console.log(`Node.js ${process.version}`)
console.log(`GC: ${typeof global.gc === 'function' ? 'yes' : 'no (use --expose-gc)'}`)
console.log(
`GC: ${typeof global.gc === 'function' ? 'yes' : 'no (use --expose-gc)'}`
)
console.log()
console.log('Loading variants...')
......@@ -280,31 +288,22 @@ console.log(` 1000 rows: ${(payload1000.length / 1024).toFixed(1)} KB`)
console.log(` 5000 rows: ${(payload5000.length / 1024).toFixed(1)} KB`)
// --- 100 rows ---
printResults(
'Table with 100 rows (baseline)',
[
printResults('Table with 100 rows (baseline)', [
runBench('Original (reviver)', origInternals, payload100, 10000),
runBench('Walk', walkInternals, payload100, 10000),
]
)
])
// --- 1000 rows ---
printResults(
'Table with 1,000 rows',
[
printResults('Table with 1,000 rows', [
runBench('Original (reviver)', origInternals, payload1000, 2000),
runBench('Walk', walkInternals, payload1000, 2000),
]
)
])
// --- 5000 rows ---
printResults(
'Table with 5,000 rows',
[
printResults('Table with 5,000 rows', [
runBench('Original (reviver)', origInternals, payload5000, 500),
runBench('Walk', walkInternals, payload5000, 500),
]
)
])
// Cleanup temp file
try {
......
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