Skip to content
Myr

Merge pull request #1182 from immerjs/feature/more-perf-benchmarks

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Improve perf benchmarking system with more versions, scenarios, and output

authored by Mark Erikson · committed by GitHub · parents 6b23c37, 20dc3aa · Browse files · 4 files+1022 added−34 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+1022 added−34 removed

  • other:+1022 added−34 removed

4 files+1022 added−34 removed

modified:perf-testing/immutability-benchmarks.mjs+993 added-17 removed
17 unmodified lines
18import {19 produce as produceMutativeCompat,20 setAutoFreeze as setAutoFreezeMutativeCompat21} from "mutative-compat"22import {23 produce as produceStructura,24 enableAutoFreeze as setAutoFreezeStructura25} from "structurajs"26import {produce as produceLimu, setAutoFreeze as setAutoFreezeLimu} from "limu"27import {bench, run, group, summary} from "mitata"2824function createInitialState() {29function createInitialState(arraySize = BENCHMARK_CONFIG.arraySize) {30 const initialState = {26 largeArray: Array.from({length: 10000}, (_, i) => ({31 largeArray: Array.from({length: arraySize}, (_, i) => ({32 id: i,33 value: Math.random(),34 nested: {key: `key-${i}`, data: Math.random()},35 moreNested: {31 items: Array.from({length: 100}, (_, i) => ({id: i, name: String(i)}))36 items: Array.from(37 {length: BENCHMARK_CONFIG.nestedArraySize},38 (_, i) => ({id: i, name: String(i)})39 )40 }41 })),34 otherData: Array.from({length: 10000}, (_, i) => ({42 otherData: Array.from({length: arraySize}, (_, i) => ({43 id: i,44 name: `name-${i}`,45 isActive: i % 2 === 038 }))46 })),47 api: {48 queries: {},49 provided: {50 keys: {}51 },52 subscriptions: {}53 }54 }55 return initialState56}5758const MAX = 15960const BENCHMARK_CONFIG = {61 iterations: 1,62 arraySize: 10000,63 nestedArraySize: 100,64 multiUpdateCount: 5,65 reuseStateIterations: 1066}6768// Utility functions for calculating array indices based on size69const getValidIndex = (arraySize = BENCHMARK_CONFIG.arraySize) => {70 // Return a valid index (not the last one to avoid edge cases)71 return Math.min(arraySize - 2, Math.max(0, arraySize - 2))72}7374const getValidId = (arraySize = BENCHMARK_CONFIG.arraySize) => {75 // Return a valid ID that exists in the array76 return Math.min(arraySize - 2, Math.max(0, arraySize - 2))77}7879const add = index => ({80 type: "test/addItem",81 payload: {id: index, value: index, nested: {data: index}}82})83const remove = index => ({type: "test/removeItem", payload: index})50const filter = index => ({type: "test/filterItem", payload: index})84const filter = percentToKeep => ({85 type: "test/filterItem",86 payload: percentToKeep87})88const update = index => ({89 type: "test/updateItem",90 payload: {id: index, value: index, nestedData: index}91})
1 unmodified line
93 type: "test/concatArray",94 payload: Array.from({length: 500}, (_, i) => ({id: i, value: index}))95})9697const updateHigh = index => ({98 type: "test/updateHighIndex",99 payload: {100 id:101 Math.floor(BENCHMARK_CONFIG.arraySize * 0.8) +102 (index % Math.floor(BENCHMARK_CONFIG.arraySize * 0.2)),103 value: index,104 nestedData: index105 }106})107const updateMultiple = index => ({108 type: "test/updateMultiple",109 payload: Array.from({length: BENCHMARK_CONFIG.multiUpdateCount}, (_, i) => ({110 id: (index + i) % BENCHMARK_CONFIG.arraySize,111 value: index + i,112 nestedData: index + i113 }))114})115const removeHigh = index => ({116 type: "test/removeHighIndex",117 payload:118 Math.floor(BENCHMARK_CONFIG.arraySize * 0.8) +119 (index % Math.floor(BENCHMARK_CONFIG.arraySize * 0.2))120})121122const sortByIdReverse = () => ({123 type: "test/sortByIdReverse"124})125126const reverseArray = () => ({127 type: "test/reverseArray"128})129130// RTKQ-style action creators131const rtkqPending = index => ({132 type: "rtkq/pending",133 payload: {134 cacheKey: `some("test-${index}-")`,135 requestId: `req-${index}`,136 id: `test-${index}-`137 }138})139140const rtkqResolved = index => ({141 type: "rtkq/resolved",142 payload: {143 cacheKey: `some("test-${index}-")`,144 requestId: `req-${index}`,145 id: `test-${index}-`,146 data: `test-${index}-1`147 }148})149150const actions = {151 add,152 remove,153 filter,154 update,65 concat155 concat,156 // dash-named fields to improve readability in benchmark results157 "update-high": updateHigh,158 "update-multiple": updateMultiple,159 "remove-high": removeHigh,160 "sortById-reverse": sortByIdReverse,161 "reverse-array": reverseArray162}163164const immerProducers = {165 // immer5: produce5,166 // immer6: produce6,71 immer7: produce7,72 immer8: produce8,73 immer9: produce9,167 // immer7: produce7,168 // immer8: produce8,169 // immer9: produce9,170 immer10: produce10,171 immer10Perf: produce10Perf172 // mutative: produceMutative,77 // mutativeCompat: produceMutativeCompat173 // mutativeCompat: produceMutativeCompat,174 // structura: produceStructura,175 // limu: produceLimu176}177178const noop = () => {}179
6 unmodified lines
186 immer9: setAutoFreeze9,187 immer10: setAutoFreeze10,188 immer10Perf: setAutoFreeze10Perf,189 mutative: noop,92 mutativeCompat: setAutoFreezeMutativeCompat190 mutativeCompat: setAutoFreezeMutativeCompat,191 structura: setAutoFreezeStructura,192 limu: setAutoFreezeLimu193}194195const setStrictIteration = {196 vanilla: noop,
4 unmodified lines
201 immer9: noop,202 immer10: noop,203 immer10Perf: noop, // setUseStrictIteration10Perf,204 mutative: noop,105 mutativeCompat: noop205 mutativeCompat: noop,206 structura: noop,207 limu: noop208}209210// RTKQ-style separate reducer functions (simulating separate RTK slices)211const updateQueries = (queries, action) => {212 switch (action.type) {213 case "rtkq/pending":214 return {215 ...queries,216 [action.payload.cacheKey]: {217 id: action.payload.id,218 status: "pending",219 data: undefined220 }221 }222 case "rtkq/resolved":223 return {224 ...queries,225 [action.payload.cacheKey]: {226 ...queries[action.payload.cacheKey],227 status: "fulfilled",228 data: action.payload.data229 }230 }231 default:232 return queries233 }234}235236const updateProvided = (provided, action) => {237 switch (action.type) {238 case "rtkq/pending":239 case "rtkq/resolved":240 return {241 ...provided,242 keys: {243 ...provided.keys,244 [action.payload.cacheKey]: {}245 }246 }247 default:248 return provided249 }250}251252const updateSubscriptions = (subscriptions, action) => {253 switch (action.type) {254 case "rtkq/pending":255 return {256 ...subscriptions,257 [action.payload.cacheKey]: {258 [action.payload.requestId]: {259 pollingInterval: 0,260 skipPollingIfUnfocused: false261 }262 }263 }264 case "rtkq/resolved":265 return subscriptions // No change on resolved266 default:267 return subscriptions268 }269}270271const vanillaReducer = (state = createInitialState(), action) => {272 switch (action.type) {273 case "test/addItem":274 return {
8 unmodified lines
283 largeArray: newArray284 }285 }286 case "test/filterItem": {287 const keepPercentage = action.payload / 10288 const length = state.largeArray.length289 const newArray = state.largeArray.filter(125 (item, i) => i !== action.payload290 (item, i) => i / length < action.payload291 )292 return {293 ...state,294 largeArray: newArray
21 unmodified lines
316 ...state,317 largeArray: newArray318 }319 }320 case "test/updateHighIndex": {321 return {322 ...state,323 largeArray: state.largeArray.map(item =>324 item.id === action.payload.id325 ? {326 ...item,327 value: action.payload.value,328 nested: {...item.nested, data: action.payload.nestedData}329 }330 : item331 )332 }333 }334 case "test/updateMultiple": {335 const updates = new Map(action.payload.map(p => [p.id, p]))336 return {337 ...state,338 largeArray: state.largeArray.map(item => {339 const update = updates.get(item.id)340 return update341 ? {342 ...item,343 value: update.value,344 nested: {...item.nested, data: update.nestedData}345 }346 : item347 })348 }349 }350 case "test/removeHighIndex": {351 const newArray = state.largeArray.slice()352 const indexToRemove = newArray.findIndex(353 item => item.id === action.payload354 )355 if (indexToRemove !== -1) {356 newArray.splice(indexToRemove, 1)357 }358 return {359 ...state,360 largeArray: newArray361 }362 }363 case "test/sortByIdReverse": {364 const newArray = state.largeArray.slice()365 newArray.sort((a, b) => b.id - a.id) // Sort by ID in reverse order366 return {367 ...state,368 largeArray: newArray369 }370 }371 case "test/reverseArray": {372 const newArray = state.largeArray.slice()373 newArray.reverse()374 return {375 ...state,376 largeArray: newArray377 }378 }379 case "rtkq/pending":380 case "rtkq/resolved": {381 // Simulate separate RTK slice reducers with combined reducer pattern382 return {383 ...state,384 api: {385 queries: updateQueries(state.api.queries, action),386 provided: updateProvided(state.api.provided, action),387 subscriptions: updateSubscriptions(state.api.subscriptions, action)388 }389 }390 }391 default:392 return state393 }394}
8 unmodified lines
403 case "test/removeItem":404 draft.largeArray.splice(action.payload, 1)405 break406 case "test/filterItem": {407 const keepPercentage = action.payload / 10408 const length = state.largeArray.length409 draft.largeArray = draft.largeArray.filter(172 (item, i) => i !== action.payload410 (item, i) => i / length < action.payload411 )412 break413 }414 case "test/updateItem": {
10 unmodified lines
425 newArray.length = length426 draft.largeArray = newArray427 break428 }429 case "test/updateHighIndex": {430 const item = draft.largeArray.find(431 item => item.id === action.payload.id432 )433 if (item) {434 item.value = action.payload.value435 item.nested.data = action.payload.nestedData436 }437 break438 }439 case "test/updateMultiple": {440 action.payload.forEach(update => {441 const item = draft.largeArray.find(item => item.id === update.id)442 if (item) {443 item.value = update.value444 item.nested.data = update.nestedData445 }446 })447 break448 }449 case "test/removeHighIndex": {450 const indexToRemove = draft.largeArray.findIndex(451 item => item.id === action.payload452 )453 if (indexToRemove !== -1) {454 draft.largeArray.splice(indexToRemove, 1)455 }456 break457 }458 case "test/sortByIdReverse": {459 draft.largeArray.sort((a, b) => b.id - a.id)460 break461 }462 case "test/reverseArray": {463 draft.largeArray.reverse()464 break465 }466 case "rtkq/pending": {467 // Simulate separate RTK slice reducers with combined reducer pattern468 const cacheKey = action.payload.cacheKey469 draft.api.queries[cacheKey] = {470 id: action.payload.id,471 status: "pending",472 data: undefined473 }474 draft.api.provided.keys[cacheKey] = {}475 draft.api.subscriptions[cacheKey] = {476 [action.payload.requestId]: {477 pollingInterval: 0,478 skipPollingIfUnfocused: false479 }480 }481 break482 }483 case "rtkq/resolved": {484 const cacheKey = action.payload.cacheKey485 draft.api.queries[cacheKey].status = "fulfilled"486 draft.api.queries[cacheKey].data = action.payload.data487 // provided and subscriptions don't change on resolved488 break489 }490 }491 })492493 return immerReducer
11 unmodified lines
505 vanilla: vanillaReducer,506 ...mapValues(immerProducers, createImmerReducer)507}508509const freeze = [false, true]510511function createBenchmarks() {512 // All single-operation benchmarks (fresh state each time)513 for (const action in actions) {514 summary(function() {515 bench(`$action: $version (freeze: $freeze)`, function*(args) {516 const version = args.get("version")
13 unmodified lines
530531 yield benchMethod532 }).args({533 version: Object.keys(reducers),232 freeze: [false, true],534 freeze,535 action: [action]536 })537 })538 }539540 // State reuse benchmarks (tests performance on frozen/evolved state)541 const reuseActions = ["update", "update-high", "remove", "remove-high"]542 for (const action of reuseActions) {543 summary(function() {544 bench(`$action-reuse: $version (freeze: $freeze)`, function*(args) {545 const version = args.get("version")546 const freeze = args.get("freeze")547 const action = args.get("action")548549 function benchMethod() {550 setAutoFreezes[version](freeze)551 setStrictIteration[version](false)552553 let currentState = createInitialState()554555 // Perform multiple operations on the same evolving state556 for (let i = 0; i < BENCHMARK_CONFIG.reuseStateIterations; i++) {557 currentState = reducers[version](currentState, actions[action](i))558 }559 setAutoFreezes[version](false)560 }561562 yield benchMethod563 }).args({564 version: Object.keys(reducers),565 freeze,566 action: [action]567 })568 })569 }570571 // Mixed operations sequence benchmark572 summary(function() {573 bench(`mixed-sequence: $version (freeze: $freeze)`, function*(args) {574 const version = args.get("version")575 const freeze = args.get("freeze")576577 function benchMethod() {578 setAutoFreezes[version](freeze)579 setStrictIteration[version](false)580581 let state = createInitialState()582583 // Perform a sequence of different operations (typical workflow)584 state = reducers[version](state, actions.add(1))585 state = reducers[version](state, actions.update(getValidId()))586 state = reducers[version](state, actions["update-high"](2))587 state = reducers[version](state, actions["update-multiple"](3))588 state = reducers[version](state, actions.remove(getValidIndex()))589590 setAutoFreezes[version](false)591 }592593 yield benchMethod594 }).args({595 version: Object.keys(reducers),596 freeze597 })598 })599600 // RTKQ-style benchmark - executes multiple reducer calls in sequence601 summary(function() {602 bench(`rtkq-sequence: $version (freeze: $freeze)`, function*(args) {603 const version = args.get("version")604 const freeze = args.get("freeze")605606 function benchMethod() {607 setAutoFreezes[version](freeze)608 setStrictIteration[version](false)609610 let state = createInitialState()611 // Use smaller array size for RTKQ benchmark due to exponential scaling612 // 100 items = ~15ms, 200 items = ~32ms, so 10000 would be impractical613 const arraySize = 100614615 // Phase 1: Execute all pending actions616 for (let i = 0; i < arraySize; i++) {617 state = reducers[version](state, rtkqPending(i))618 }619620 // Phase 2: Execute all resolved actions621 for (let i = 0; i < arraySize; i++) {622 state = reducers[version](state, rtkqResolved(i))623 }624625 setAutoFreezes[version](false)626 }627628 yield benchMethod629 }).args({630 version: Object.keys(reducers),631 freeze632 })633 })634}635636// Summary table functionality637function extractBenchmarkData(benchmarks) {638 const data = []639640 for (const trial of benchmarks) {641 for (const run of trial.runs) {642 if (run.error || !run.stats) continue643644 // Parse benchmark name to extract scenario, version, and freeze setting645 // Expected format: "scenario: version (freeze: true/false)"646 const match = run.name.match(647 /^(.+?):\s*(.+?)\s*\(freeze:\s*(true|false)\)$/648 )649 if (!match) continue650651 const [, scenario, version, freeze] = match652 const freezeIndicator = freeze === "true" ? "f+" : "f-"653 const versionKey = `${version.trim()}|${freezeIndicator}`654655 data.push({656 scenario: scenario.trim(),657 version: version.trim(),658 freeze: freeze === "true",659 freezeIndicator,660 versionKey,661 avgTime: run.stats.avg,662 stats: run.stats663 })664 }665 }666667 return data668}669670function organizeBenchmarkMatrix(data) {671 const matrix = {}672 const scenarios = new Set()673 const versions = new Set()674675 // Organize data into matrix structure676 for (const item of data) {677 scenarios.add(item.scenario)678 versions.add(item.versionKey)679680 if (!matrix[item.scenario]) {681 matrix[item.scenario] = {}682 }683684 matrix[item.scenario][item.versionKey] = {685 avgTime: item.avgTime,686 stats: item.stats687 }688 }689690 return {691 matrix,692 scenarios: Array.from(scenarios).sort(),693 versions: Array.from(versions).sort()694 }695}696697function calculateRelativePerformanceAndRankings(matrix, scenarios, versions) {698 const relativeData = {}699 const rankings = {}700701 for (const scenario of scenarios) {702 const scenarioData = matrix[scenario] || {}703 const validVersions = versions.filter(v => scenarioData[v])704705 if (validVersions.length === 0) continue706707 // Find fastest time for this scenario708 const times = validVersions.map(v => ({709 version: v,710 time: scenarioData[v].avgTime711 }))712713 times.sort((a, b) => a.time - b.time)714 const fastestTime = times[0].time715716 // Calculate relative performance and rankings717 relativeData[scenario] = {}718 rankings[scenario] = {}719720 times.forEach((item, index) => {721 const multiplier = item.time / fastestTime722 relativeData[scenario][item.version] = multiplier723 rankings[scenario][item.version] = index + 1724 })725 }726727 return {relativeData, rankings}728}729730function formatTime(nanoseconds) {731 // Use similar formatting to Mitata's $.time function, but more compact732 if (nanoseconds < 1) return `${(nanoseconds * 1e3).toFixed(1)}ps`733 if (nanoseconds < 1e3) return `${nanoseconds.toFixed(1)}ns`734735 let ns = nanoseconds / 1000736 if (ns < 1e3) return `${ns.toFixed(1)}µs`737738 ns /= 1000739 if (ns < 1e3) return `${ns.toFixed(1)}ms`740741 ns /= 1000742 if (ns < 1e3) return `${ns.toFixed(1)}s`743744 return `${ns.toFixed(1)}s`745}746747function formatRanking(rank) {748 const suffixes = ["th", "st", "nd", "rd"]749 const suffix = rank >= 11 && rank <= 13 ? "th" : suffixes[rank % 10] || "th"750 return `${rank}${suffix}`751}752753function formatMultiplier(relative) {754 if (relative === 1) return "1.0x"755756 // If the multiplier is 4+ digits (1000+), don't show decimals757 if (relative >= 1000) {758 return `${Math.round(relative)}x`759 }760761 return `${relative.toFixed(1)}x`762}763764function shortenVersionName(versionName) {765 // Special case common long version names to save space766 const shortNames = {767 immer10Perf: "i10Perf",768 immer10: "i10",769 immer5: "i5",770 immer6: "i6",771 immer7: "i7",772 immer8: "i8",773 immer9: "i9",774 mutativeCompat: "mutatv-c",775 mutative: "mutatv",776 structura: "struct",777 vanilla: "vanilla"778 }779780 return shortNames[versionName] || versionName781}782783function formatScenarioName(scenario, maxWidth) {784 // If the scenario contains hyphens and is too long, split on hyphens785 // and display on multiple lines within the cell786 if (scenario.includes("-") && scenario.length > maxWidth) {787 const parts = scenario.split("-")788 return parts789 }790791 // For non-hyphenated scenarios, truncate if needed792 if (scenario.length > maxWidth) {793 return [scenario.substring(0, maxWidth - 2) + ".."]794 }795796 return [scenario]797}798799function printSummaryTable(800 matrix,801 scenarios,802 versions,803 relativeData,804 rankings805) {806 console.log("\n")807 console.log("=".repeat(80))808 console.log("BENCHMARK SUMMARY TABLE")809 console.log("=".repeat(80))810811 if (scenarios.length === 0 || versions.length === 0) {812 console.log("No benchmark data available for summary table.")813 return814 }815816 // Parse version keys to get version names and freeze indicators817 const versionInfo = versions.map(v => {818 const [versionName, freezeIndicator] = v.split("|")819 const shortName = shortenVersionName(versionName)820 return {821 key: v,822 name: shortName,823 freeze: freezeIndicator,824 originalName: versionName825 }826 })827828 // Fixed column widths for consistent alignment - 9 chars content + separators829 const scenarioWidth = 9830 const versionWidth = 8831832 // Print header with 9-char content + padding833 let header = "┌" + "─".repeat(scenarioWidth + 2)834 for (let i = 0; i < versions.length; i++) {835 header += "┬" + "─".repeat(versionWidth)836 }837 header += "┐"838 console.log(header)839840 // Print column headers - version names841 let headerRow1 = "│ " + "Scenario".padEnd(scenarioWidth) + " "842 for (const vInfo of versionInfo) {843 headerRow1 += "│" + vInfo.name.padEnd(versionWidth)844 }845 headerRow1 += "│"846 console.log(headerRow1)847848 // Print column headers - freeze indicators849 let headerRow2 = "│ " + "".padEnd(scenarioWidth) + " "850 for (const vInfo of versionInfo) {851 headerRow2 += "│" + vInfo.freeze.padEnd(versionWidth)852 }853 headerRow2 += "│"854 console.log(headerRow2)855856 // Print separator857 let separator = "├" + "─".repeat(scenarioWidth + 2)858 for (let i = 0; i < versions.length; i++) {859 separator += "┼" + "─".repeat(versionWidth)860 }861 separator += "┤"862 console.log(separator)863864 // Print data rows (now 3+ lines per scenario depending on scenario name length)865 for (const scenario of scenarios) {866 const scenarioData = matrix[scenario] || {}867868 // Format scenario name, potentially splitting on hyphens869 const scenarioParts = formatScenarioName(scenario, scenarioWidth)870 const maxLines = Math.max(3, scenarioParts.length) // At least 3 lines for data871872 // Print all lines for this scenario873 for (let lineIndex = 0; lineIndex < maxLines; lineIndex++) {874 let row = "│ "875876 // Scenario column content877 if (lineIndex < scenarioParts.length) {878 row += scenarioParts[lineIndex].padEnd(scenarioWidth)879 } else {880 row += "".padEnd(scenarioWidth)881 }882 row += " "883884 // Version columns content885 for (const version of versions) {886 let cellContent = ""887888 if (lineIndex === 0) {889 // First line: absolute times890 const data = scenarioData[version]891 let timeStr = data ? formatTime(data.avgTime) : "N/A"892 if (timeStr.length > versionWidth) {893 timeStr = timeStr.substring(0, versionWidth - 1) + "…"894 }895 cellContent = timeStr896 } else if (lineIndex === 1) {897 // Second line: relative performance multipliers898 const relative = relativeData[scenario]?.[version]899 if (relative) {900 cellContent = formatMultiplier(relative)901 } else {902 cellContent = "N/A"903 }904 if (cellContent.length > versionWidth) {905 cellContent = cellContent.substring(0, versionWidth - 1) + "…"906 }907 } else if (lineIndex === 2) {908 // Third line: rankings909 const ranking = rankings[scenario]?.[version]910 if (ranking) {911 cellContent = `(${formatRanking(ranking)})`912 }913 }914 // Lines beyond 2 are empty for version columns915916 row += "│" + cellContent.padEnd(versionWidth)917 }918919 row += "│"920 console.log(row)921 }922923 // Add separator between scenarios (except for last one)924 if (scenario !== scenarios[scenarios.length - 1]) {925 let rowSep = "├" + "─".repeat(scenarioWidth + 2)926 for (let i = 0; i < versions.length; i++) {927 rowSep += "┼" + "─".repeat(versionWidth)928 }929 rowSep += "┤"930 console.log(rowSep)931 }932 }933934 // Print footer935 let footer = "└" + "─".repeat(scenarioWidth + 2)936 for (let i = 0; i < versions.length; i++) {937 footer += "┴" + "─".repeat(versionWidth)938 }939 footer += "┘"940 console.log(footer)941942 console.log("\nNotes:")943 console.log("- f+ = freeze enabled, f- = freeze disabled")944 console.log("- Line 1: absolute execution time")945 console.log("- Line 2: relative performance multiplier")946 console.log("- Line 3: ranking (1st = fastest, 2nd = second fastest, etc.)")947 console.log("- 1.00x indicates the fastest version for that scenario")948}949950// Performance improvement analysis between immer10Perf and immer10 (freeze: true)951function calculateImmer10PerfImprovement(matrix, scenarios) {952 const baselineKey = "immer10|f+"953 const improvedKey = "immer10Perf|f+"954955 const improvements = []956957 for (const scenario of scenarios) {958 const scenarioData = matrix[scenario] || {}959 const baselineData = scenarioData[baselineKey]960 const improvedData = scenarioData[improvedKey]961962 if (baselineData && improvedData) {963 const baselineTime = baselineData.avgTime964 const improvedTime = improvedData.avgTime965966 // Calculate percentage improvement: ((baseline - improved) / baseline) * 100967 // Positive = improvement, negative = regression968 const improvement = ((baselineTime - improvedTime) / baselineTime) * 100969970 improvements.push({971 scenario,972 baselineTime,973 improvedTime,974 improvement975 })976 }977 }978979 if (improvements.length === 0) {980 return null981 }982983 const improvementValues = improvements.map(i => i.improvement)984 const minImprovement = Math.min(...improvementValues)985 const maxImprovement = Math.max(...improvementValues)986 const avgImprovement =987 improvementValues.reduce((sum, val) => sum + val, 0) /988 improvementValues.length989990 return {991 improvements,992 stats: {993 min: minImprovement,994 max: maxImprovement,995 avg: avgImprovement,996 count: improvements.length997 }998 }999}10001001// Calculate overall version scores using geometric mean of relative performance1002function calculateOverallVersionScores(relativeData, scenarios, versions) {1003 const versionScores = []10041005 for (const version of versions) {1006 const multipliers = []10071008 // Collect all relative performance multipliers for this version1009 for (const scenario of scenarios) {1010 const relative = relativeData[scenario]?.[version]1011 if (relative && relative > 0) {1012 multipliers.push(relative)1013 }1014 }10151016 if (multipliers.length === 0) continue10171018 // Calculate geometric mean: nth root of product of all values1019 // For performance data, geometric mean is more appropriate than arithmetic mean1020 const product = multipliers.reduce((prod, val) => prod * val, 1)1021 const geometricMean = Math.pow(product, 1 / multipliers.length)10221023 versionScores.push({1024 version,1025 geometricMean,1026 scenarioCount: multipliers.length1027 })1028 }10291030 // Sort by geometric mean (lower is better - closer to 1.0x means consistently fast)1031 versionScores.sort((a, b) => a.geometricMean - b.geometricMean)10321033 // Add rankings1034 versionScores.forEach((score, index) => {1035 score.rank = index + 11036 })10371038 return versionScores1039}10401041function printImmer10PerfComparison(improvementData) {1042 console.log("\n")1043 console.log("=".repeat(80))1044 console.log("IMMER10PERF vs IMMER10 PERFORMANCE COMPARISON (freeze: true)")1045 console.log("=".repeat(80))10461047 if (!improvementData) {1048 console.log(1049 "No comparable data found between immer10Perf and immer10 (freeze: true)"1050 )1051 return1052 }10531054 const {stats, improvements} = improvementData10551056 console.log(`\nSummary Statistics (${stats.count} scenarios):`)1057 console.log(1058 ` Average Improvement: ${stats.avg >= 0 ? "+" : ""}${stats.avg.toFixed(1059 11060 )}%`1061 )1062 console.log(1063 ` Best Improvement: ${stats.max >= 0 ? "+" : ""}${stats.max.toFixed(1064 11065 )}%`1066 )1067 console.log(1068 ` Worst Improvement: ${stats.min >= 0 ? "+" : ""}${stats.min.toFixed(1069 11070 )}%`1071 )10721073 // Show per-scenario breakdown1074 console.log("\nPer-Scenario Breakdown:")1075 console.log(1076 "┌─────────────────────┬──────────────┬──────────────┬─────────────┐"1077 )1078 console.log(1079 "│ Scenario │ immer10 │ immer10Perf │ Improvement │"1080 )1081 console.log(1082 "├─────────────────────┼──────────────┼──────────────┼─────────────┤"1083 )10841085 // Sort by improvement (best first)1086 const sortedImprovements = [...improvements].sort(1087 (a, b) => b.improvement - a.improvement1088 )10891090 for (const item of sortedImprovements) {1091 const scenario = item.scenario.padEnd(19).substring(0, 19)1092 const baseline = formatTime(item.baselineTime).padStart(12)1093 const improved = formatTime(item.improvedTime).padStart(12)1094 const improvement = `${1095 item.improvement >= 0 ? "+" : ""1096 }${item.improvement.toFixed(1)}%`.padStart(11)10971098 console.log(`│ ${scenario} │ ${baseline} │ ${improved} │ ${improvement} │`)1099 }11001101 console.log(1102 "└─────────────────────┴──────────────┴──────────────┴─────────────┘"1103 )11041105 // Interpretation1106 if (stats.avg > 0) {1107 console.log(1108 `\n✓ immer10Perf shows an average ${stats.avg.toFixed(1109 11110 )}% performance improvement over immer10`1111 )1112 } else {1113 console.log(1114 `\n⚠ immer10Perf shows an average ${Math.abs(stats.avg).toFixed(1115 11116 )}% performance regression vs immer10`1117 )1118 }1119}11201121function printOverallVersionRankings(versionScores) {1122 console.log("\n")1123 console.log("=".repeat(80))1124 console.log(1125 "OVERALL VERSION RANKINGS (Geometric Mean of Relative Performance)"1126 )1127 console.log("=".repeat(80))11281129 if (versionScores.length === 0) {1130 console.log("No version data available for overall rankings.")1131 return1132 }11331134 console.log(1135 "\nMethodology: Lower geometric mean = better overall performance"1136 )1137 console.log(1138 "(Geometric mean is standard for benchmarking as it handles multiplicative performance differences)"1139 )11401141 console.log("\n┌──────┬─────────────────────┬─────────────────┬───────────┐")1142 console.log("│ Rank │ Version │ Geometric Mean │ Scenarios │")1143 console.log("├──────┼─────────────────────┼─────────────────┼───────────┤")11441145 for (const score of versionScores) {1146 const [versionName, freezeIndicator] = score.version.split("|")1147 const shortName = shortenVersionName(versionName)1148 const displayName = `${shortName} (${freezeIndicator})`1149 .padEnd(19)1150 .substring(0, 19)1151 const rank = score.rank.toString().padStart(4)1152 const geoMean = `${score.geometricMean.toFixed(2)}x`.padStart(15)1153 const scenarios = score.scenarioCount.toString().padStart(9)11541155 console.log(`│ ${rank} │ ${displayName} │ ${geoMean} │ ${scenarios} │`)1156 }11571158 console.log("└──────┴─────────────────────┴─────────────────┴───────────┘")11591160 // Highlight top performers1161 if (versionScores.length >= 3) {1162 console.log("\nTop Overall Performers:")1163 for (let i = 0; i < Math.min(10, versionScores.length); i++) {1164 const score = versionScores[i]1165 const [versionName, freezeIndicator] = score.version.split("|")1166 const shortName = shortenVersionName(versionName)1167 console.log(1168 ` ${i +1169 1}. ${shortName} (${freezeIndicator}) - ${score.geometricMean.toFixed(1170 21171 )}x average`1172 )1173 }1174 }1175}11761177function printBenchmarkSummaryTable(benchmarks) {1178 try {1179 const data = extractBenchmarkData(benchmarks)1180 if (data.length === 0) {1181 console.log("\nNo valid benchmark data found for summary table.")1182 return1183 }11841185 const {matrix, scenarios, versions} = organizeBenchmarkMatrix(data)1186 const {relativeData, rankings} = calculateRelativePerformanceAndRankings(1187 matrix,1188 scenarios,1189 versions1190 )11911192 // Print main summary table1193 printSummaryTable(matrix, scenarios, versions, relativeData, rankings)11941195 // Print immer10Perf vs immer10 comparison1196 const improvementData = calculateImmer10PerfImprovement(matrix, scenarios)1197 printImmer10PerfComparison(improvementData)11981199 // Print overall version rankings1200 const versionScores = calculateOverallVersionScores(1201 relativeData,1202 scenarios,1203 versions1204 )1205 printOverallVersionRankings(versionScores)1206 } catch (error) {1207 console.error("\nError generating summary table:", error.message)1208 }1209}12101211async function main() {1212 createBenchmarks()241 await run()1213 const results = await run()12141215 // Generate and print summary table1216 printBenchmarkSummaryTable(results.benchmarks)12171218 process.exit(0)1219}12201221main()
modified:perf-testing/package.json+5 added-3 removed
modified:perf-testing/read-cpuprofile.js+10 added-4 removed
1import fs from "fs"2import {SourceMapConsumer} from "source-map"34const profileName = process.argv[2]4let profileName = process.argv[2]56if (!profileName) {7 const cpuProfiles = fs.readdirSync(".").filter(f => f.endsWith(".cpuprofile"))8 const [lastProfile] = cpuProfiles.slice(-1)6if (!profileName || !fs.existsSync(profileName)) {7 console.error("Usage: node read-cpuprofile.js <path-to-cpuprofile>")8 process.exit(1)9 if (!lastProfile) {10 console.error("Usage: node read-cpuprofile.js <path-to-cpuprofile>")11 process.exit(1)12 }13 console.log("Using latest profile: ", lastProfile)14 profileName = lastProfile15}1617const profile = JSON.parse(fs.readFileSync(profileName, "utf8"))18
551 unmodified lines
modified:perf-testing/yarn.lock+14 added-10 removed
146 unmodified lines
147 version "10.1.3"148 resolved "https://registry.yarnpkg.com/immer/-/immer-10.1.3.tgz#e38a0b97db59949d31d9b381b04c2e441b1c3747"149 integrity sha512-tmjF/k8QDKydUlm3mZU+tjM6zeq9/fFpPqH9SzWmBnVVKsPBg/V66qsMwb3/Bo90cgUN+ghdVBess+hPsxUyRw==150151"immer10Perf@file:..":152 version "10.0.3-beta"153151"immer5@npm:immer@5":152 version "5.3.6"153 resolved "https://registry.yarnpkg.com/immer/-/immer-5.3.6.tgz#51eab8cbbeb13075fe2244250f221598818cac04"154 integrity sha512-pqWQ6ozVfNOUDjrLfm4Pt7q4Q12cGw2HUZgry4Q5+Myxu9nmHRkWBpI0J4+MK0AxbdFtdMTwEGVl7Vd+vEiK+A==
17 unmodified lines
172 version "9.0.21"173 resolved "https://registry.yarnpkg.com/immer/-/immer-9.0.21.tgz#1e025ea31a40f24fb064f1fef23e931496330176"174 integrity sha512-bc4NBHqOqSfRW7POMkHd51LvClaeMXpm8dx0e8oE2GORbq5aRK7Bxl4FyzVLdGtLmvLKL7BTDBG5ACQm4HWjTA==175179"immer@file:..":180 version "10.0.3-beta"181176isexe@^2.0.0:177 version "2.0.0"178 resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"179 integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==180181limu@^4.1.1:182 version "4.1.1"183 resolved "https://registry.yarnpkg.com/limu/-/limu-4.1.1.tgz#28950b32f7f09cb35843a258dc38e55f21ae90c3"184 integrity sha512-IkMC00X9uc1HnSm3uPeuKKraEdRjbAqoVPzQfma8nupXoNdJ9fcPsHYUTswjZsyxMz03dQB9Q11MWzEyggyfqg==185186mitata@^1.0.34:187 version "1.0.34"188 resolved "https://registry.yarnpkg.com/mitata/-/mitata-1.0.34.tgz#131f500d58c0bdc958095ab64f637d6fe1cf101a"189 integrity sha512-Mc3zrtNBKIMeHSCQ0XqRLo1vbdIx1wvFV9c8NJAiyho6AjNfMY8bVhbS12bwciUdd1t4rj8099CH3N3NFahaUA==
2 unmodified lines
192 version "0.1.2"193 resolved "https://registry.yarnpkg.com/mutative-compat/-/mutative-compat-0.1.2.tgz#d1926069e42de35e3754458fcd37754339bf3bf6"194 integrity sha512-XF+l3jkY4XGZ2IZzdkS0tu0DtYsKJZcSQcoxHu+gvHkNWS1Xd+B4yOLqbhFAx46jzuB4BWIN/SoXB1E5yDAKjg==195197mutative@^1.1.0:198 version "1.2.0"199 resolved "https://registry.yarnpkg.com/mutative/-/mutative-1.2.0.tgz#db75b60b436ad0a940e2e47bffb6661dd77c2754"200 integrity sha512-1muFw45Lwjso6TSBGiXfbjKS01fVSD/qaqBfTo/gXgp79e8KM4Sa1XP/S4iN2/DvSdIZgjFJI+JIhC7eKf3GTg==196mutative@^1.3.0:197 version "1.3.0"198 resolved "https://registry.yarnpkg.com/mutative/-/mutative-1.3.0.tgz#9cb4f216813267487fadfae794881ed6ee69f444"199 integrity sha512-8MJj6URmOZAV70dpFe1YnSppRTKC4DsMkXQiBDFayLcDI4ljGokHxmpqaBQuDWa4iAxWaJJ1PS8vAmbntjjKmQ==200201path-key@^3.1.0:202 version "3.1.1"203 resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375"
56 unmodified lines
260 version "0.7.6"261 resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.7.6.tgz#a3658ab87e5b6429c8a1f3ba0083d4c61ca3ef02"262 integrity sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==263264structurajs@^0.12.6:265 version "0.12.6"266 resolved "https://registry.yarnpkg.com/structurajs/-/structurajs-0.12.6.tgz#9d4bc717e43f62d5a6dd50feec92de2e2837bc0d"267 integrity sha512-V3UTJ2XMJSoIfeH2S6eJwT6HrsgN5uZ0htj2xLLyOtopjKtiix0BcRJv+U53njccwLsVzV3DXukx6X1Dphiu+Q==268269tslib@^2.4.0:270 version "2.8.1"271 resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f"272 integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==
7 unmodified lines