Skip to content
Myr

immutability-profiling.mjs

This file

Path

perf-testing/immutability-profiling.mjs

562 lines · 14.3 KiB · JavaScript

Last changed by

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

History of this file

Take it

1/* eslint-disable no-inner-declarations */2import {produce, setAutoFreeze, enableArrayMethods} from "../dist/immer.mjs"34enableArrayMethods()5// ============================================================================6// CONFIGURATION7// ============================================================================89const PROFILING_CONFIG = {10	// How many times to run each scenario (can be overridden via CLI)11	iterations: parseInt(process.argv[2]) || 100,1213	// Which scenarios to run14	scenarios: [15		// Single operations16		"add",17		"remove",18		"update",19		"update-high",20		"update-multiple",21		"remove-high",22		"update-largeObject1",23		"update-largeObject2",24		"concat",25		"mapNested",26		"sortById-reverse",27		"reverse-array",2829		// Reuse scenarios (state evolution)30		"update-reuse",31		"update-high-reuse",32		"remove-reuse",33		"remove-high-reuse",34		"update-largeObject1-reuse",35		"update-largeObject2-reuse",3637		// Complex sequences38		"mixed-sequence",39		"rtkq-sequence"40	]41}4243const BENCHMARK_CONFIG = {44	arraySize: 100,45	nestedArraySize: 10,46	largeObjectSize1: 1000,47	largeObjectSize2: 3000,48	multiUpdateCount: 5,49	reuseStateIterations: 1050}5152const MAX = 15354// ============================================================================55// UTILITY FUNCTIONS56// ============================================================================5758function createInitialState(arraySize = BENCHMARK_CONFIG.arraySize) {59	const initialState = {60		largeArray: Array.from({length: arraySize}, (_, i) => ({61			id: i,62			value: Math.random(),63			nested: {key: `key-${i}`, data: Math.random()},64			moreNested: {65				items: Array.from(66					{length: BENCHMARK_CONFIG.nestedArraySize},67					(_, i) => ({id: i, name: String(i)})68				)69			}70		})),71		otherData: Array.from({length: arraySize}, (_, i) => ({72			id: i,73			name: `name-${i}`,74			isActive: i % 2 === 075		})),76		largeObject1: createLargeObject(BENCHMARK_CONFIG.largeObjectSize1),77		largeObject2: createLargeObject(BENCHMARK_CONFIG.largeObjectSize2),78		api: {79			queries: {},80			provided: {81				keys: {}82			},83			subscriptions: {}84		}85	}86	return initialState87}8889function createLargeObject(size = 100) {90	const obj = {}91	for (let i = 0; i < size; i++) {92		obj[`property${i}`] = {93			id: i,94			value: Math.random(),95			name: `item-${i}`,96			active: i % 2 === 097		}98	}99	return obj100}101102const getValidIndex = (arraySize = BENCHMARK_CONFIG.arraySize) => {103	return Math.min(arraySize - 2, Math.max(0, arraySize - 2))104}105106const getValidId = (arraySize = BENCHMARK_CONFIG.arraySize) => {107	return Math.min(arraySize - 2, Math.max(0, arraySize - 2))108}109110// ============================================================================111// ACTION CREATORS112// ============================================================================113114const add = index => ({115	type: "test/addItem",116	payload: {id: index, value: index, nested: {data: index}}117})118119const remove = index => ({type: "test/removeItem", payload: index})120121const update = index => ({122	type: "test/updateItem",123	payload: {id: index, value: index, nestedData: index}124})125126const updateLargeObject1 = index => ({127	type: "test/updateLargeObject1",128	payload: {value: index}129})130131const updateLargeObject2 = index => ({132	type: "test/updateLargeObject2",133	payload: {value: index}134})135136const concat = index => ({137	type: "test/concatArray",138	payload: Array.from({length: 500}, (_, i) => ({id: i, value: index}))139})140141const mapNested = () => ({142	type: "test/mapNested"143})144145const updateHigh = index => ({146	type: "test/updateHighIndex",147	payload: {148		id:149			Math.floor(BENCHMARK_CONFIG.arraySize * 0.8) +150			(index % Math.floor(BENCHMARK_CONFIG.arraySize * 0.2)),151		value: index,152		nestedData: index153	}154})155156const updateMultiple = index => ({157	type: "test/updateMultiple",158	payload: Array.from({length: BENCHMARK_CONFIG.multiUpdateCount}, (_, i) => ({159		id: (index + i) % BENCHMARK_CONFIG.arraySize,160		value: index + i,161		nestedData: index + i162	}))163})164165const removeHigh = index => ({166	type: "test/removeHighIndex",167	payload:168		Math.floor(BENCHMARK_CONFIG.arraySize * 0.8) +169		(index % Math.floor(BENCHMARK_CONFIG.arraySize * 0.2))170})171172const sortByIdReverse = () => ({173	type: "test/sortByIdReverse"174})175176const reverseArray = () => ({177	type: "test/reverseArray"178})179180const rtkqPending = index => ({181	type: "rtkq/pending",182	payload: {183		cacheKey: `some("test-${index}-")`,184		requestId: `req-${index}`,185		id: `test-${index}-`186	}187})188189const rtkqResolved = index => ({190	type: "rtkq/resolved",191	payload: {192		cacheKey: `some("test-${index}-")`,193		requestId: `req-${index}`,194		id: `test-${index}-`,195		data: `test-${index}-1`196	}197})198199const actions = {200	add,201	remove,202	update,203	concat,204	mapNested,205	"update-largeObject1": updateLargeObject1,206	"update-largeObject2": updateLargeObject2,207	"update-high": updateHigh,208	"update-multiple": updateMultiple,209	"remove-high": removeHigh,210	"sortById-reverse": sortByIdReverse,211	"reverse-array": reverseArray212}213214// ============================================================================215// REDUCER IMPLEMENTATION216// ============================================================================217218const immerReducer = (state = createInitialState(), action) =>219	produce(state, draft => {220		switch (action.type) {221			case "test/addItem":222				draft.largeArray.push(action.payload)223				break224			case "test/removeItem":225				draft.largeArray.splice(action.payload, 1)226				break227			case "test/updateItem": {228				const item = draft.largeArray.find(229					item => item.id === action.payload.id230				)231				item.value = action.payload.value232				item.nested.data = action.payload.nestedData233				break234			}235			case "test/updateLargeObject1": {236				draft.largeObject1[`propertyAdded${action.payload.value}`] = {237					id: action.payload.value238				}239				break240			}241			case "test/updateLargeObject2": {242				draft.largeObject2[`propertyAdded${action.payload.value}`] = {243					id: action.payload.value244				}245				break246			}247			case "test/concatArray": {248				const length = state.largeArray.length249				const newArray = action.payload.concat(state.largeArray)250				newArray.length = length251				draft.largeArray = newArray252				break253			}254			case "test/mapNested": {255				draft.otherData = draft.largeArray.map(item => item.nested)256				break257			}258			case "test/updateHighIndex": {259				const item = draft.largeArray.find(260					item => item.id === action.payload.id261				)262				if (item) {263					item.value = action.payload.value264					item.nested.data = action.payload.nestedData265				}266				break267			}268			case "test/updateMultiple": {269				action.payload.forEach(update => {270					const item = draft.largeArray.find(item => item.id === update.id)271					if (item) {272						item.value = update.value273						item.nested.data = update.nestedData274					}275				})276				break277			}278			case "test/removeHighIndex": {279				const indexToRemove = draft.largeArray.findIndex(280					item => item.id === action.payload281				)282				if (indexToRemove !== -1) {283					draft.largeArray.splice(indexToRemove, 1)284				}285				break286			}287			case "test/sortByIdReverse": {288				draft.largeArray.sort((a, b) => b.id - a.id)289				break290			}291			case "test/reverseArray": {292				draft.largeArray.reverse()293				break294			}295			case "rtkq/pending": {296				const cacheKey = action.payload.cacheKey297				draft.api.queries[cacheKey] = {298					id: action.payload.id,299					status: "pending",300					data: undefined301				}302				draft.api.provided.keys[cacheKey] = {}303				draft.api.subscriptions[cacheKey] = {304					[action.payload.requestId]: {305						pollingInterval: 0,306						skipPollingIfUnfocused: false307					}308				}309				break310			}311			case "rtkq/resolved": {312				const cacheKey = action.payload.cacheKey313				draft.api.queries[cacheKey].status = "fulfilled"314				draft.api.queries[cacheKey].data = action.payload.data315				break316			}317		}318	})319320// ============================================================================321// SCENARIO FUNCTIONS322// ============================================================================323324// Single operation scenarios - execute once325function scenario_add() {326	const initialState = createInitialState()327	for (let j = 0; j < MAX; j++) {328		immerReducer(initialState, actions.add(j))329	}330}331332function scenario_remove() {333	const initialState = createInitialState()334	for (let j = 0; j < MAX; j++) {335		immerReducer(initialState, actions.remove(j))336	}337}338339function scenario_update() {340	const initialState = createInitialState()341	for (let j = 0; j < MAX; j++) {342		immerReducer(initialState, actions.update(j))343	}344}345346function scenario_update_high() {347	const initialState = createInitialState()348	for (let j = 0; j < MAX; j++) {349		immerReducer(initialState, actions["update-high"](j))350	}351}352353function scenario_update_multiple() {354	const initialState = createInitialState()355	for (let j = 0; j < MAX; j++) {356		immerReducer(initialState, actions["update-multiple"](j))357	}358}359360function scenario_remove_high() {361	const initialState = createInitialState()362	for (let j = 0; j < MAX; j++) {363		immerReducer(initialState, actions["remove-high"](j))364	}365}366367function scenario_update_largeObject1() {368	const initialState = createInitialState()369	for (let j = 0; j < MAX; j++) {370		immerReducer(initialState, actions["update-largeObject1"](j))371	}372}373374function scenario_update_largeObject2() {375	const initialState = createInitialState()376	for (let j = 0; j < MAX; j++) {377		immerReducer(initialState, actions["update-largeObject2"](j))378	}379}380381function scenario_concat() {382	const initialState = createInitialState()383	for (let j = 0; j < MAX; j++) {384		immerReducer(initialState, actions.concat(j))385	}386}387388function scenario_mapNested() {389	const initialState = createInitialState()390	for (let j = 0; j < MAX; j++) {391		immerReducer(initialState, actions.mapNested())392	}393}394395function scenario_sortById_reverse() {396	const initialState = createInitialState()397	for (let j = 0; j < MAX; j++) {398		immerReducer(initialState, actions["sortById-reverse"]())399	}400}401402function scenario_reverse_array() {403	const initialState = createInitialState()404	for (let j = 0; j < MAX; j++) {405		immerReducer(initialState, actions["reverse-array"]())406	}407}408409// Reuse scenarios - execute full state evolution sequence once410function scenario_update_reuse() {411	let currentState = createInitialState()412413	for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {414		currentState = immerReducer(currentState, actions.update(j))415	}416}417418function scenario_update_high_reuse() {419	let currentState = createInitialState()420421	for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {422		currentState = immerReducer(currentState, actions["update-high"](j))423	}424}425426function scenario_remove_reuse() {427	let currentState = createInitialState()428429	for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {430		currentState = immerReducer(currentState, actions.remove(j))431	}432}433434function scenario_remove_high_reuse() {435	let currentState = createInitialState()436437	for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {438		currentState = immerReducer(currentState, actions["remove-high"](j))439	}440}441442function scenario_update_largeObject1_reuse() {443	let currentState = createInitialState()444445	for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {446		currentState = immerReducer(currentState, actions["update-largeObject1"](j))447	}448}449450function scenario_update_largeObject2_reuse() {451	let currentState = createInitialState()452453	for (let j = 0; j < BENCHMARK_CONFIG.reuseStateIterations; j++) {454		currentState = immerReducer(currentState, actions["update-largeObject2"](j))455	}456}457458// Complex sequence scenarios - execute full sequence once459function scenario_mixed_sequence() {460	let state = createInitialState()461	state = immerReducer(state, actions.add(1))462	state = immerReducer(state, actions.update(getValidId()))463	state = immerReducer(state, actions["update-high"](2))464	state = immerReducer(state, actions["update-multiple"](3))465	state = immerReducer(state, actions.remove(getValidIndex()))466}467468function scenario_rtkq_sequence() {469	let state = createInitialState()470	const arraySize = 100471472	// Phase 1: Execute all pending actions473	for (let j = 0; j < arraySize; j++) {474		state = immerReducer(state, rtkqPending(j))475	}476477	// Phase 2: Execute all resolved actions478	for (let j = 0; j < arraySize; j++) {479		state = immerReducer(state, rtkqResolved(j))480	}481}482483// ============================================================================484// SCENARIO REGISTRY485// ============================================================================486487const scenarios = {488	// Single operations489	add: scenario_add,490	remove: scenario_remove,491	update: scenario_update,492	"update-high": scenario_update_high,493	"update-multiple": scenario_update_multiple,494	"remove-high": scenario_remove_high,495	"update-largeObject1": scenario_update_largeObject1,496	"update-largeObject2": scenario_update_largeObject2,497	concat: scenario_concat,498	mapNested: scenario_mapNested,499	"sortById-reverse": scenario_sortById_reverse,500	"reverse-array": scenario_reverse_array,501502	// Reuse scenarios503	"update-reuse": scenario_update_reuse,504	"update-high-reuse": scenario_update_high_reuse,505	"remove-reuse": scenario_remove_reuse,506	"remove-high-reuse": scenario_remove_high_reuse,507	"update-largeObject1-reuse": scenario_update_largeObject1_reuse,508	"update-largeObject2-reuse": scenario_update_largeObject2_reuse,509510	// Complex sequences511	"mixed-sequence": scenario_mixed_sequence,512	"rtkq-sequence": scenario_rtkq_sequence513}514515// ============================================================================516// MAIN EXECUTION517// ============================================================================518519function main() {520	// Set freeze to true (default Immer behavior)521	setAutoFreeze(true)522523	console.log("=".repeat(80))524	console.log("IMMER PROFILING SCRIPT (freeze: true)")525	console.log("=".repeat(80))526	console.log(`Iterations per scenario: ${PROFILING_CONFIG.iterations}`)527	console.log(`Total scenarios: ${PROFILING_CONFIG.scenarios.length}`)528	console.log("=".repeat(80))529	console.log()530531	let completed = 0532	for (const scenarioName of PROFILING_CONFIG.scenarios) {533		const scenarioFn = scenarios[scenarioName]534		if (!scenarioFn) {535			console.log(`⚠ Skipping unknown scenario: ${scenarioName}`)536			continue537		}538539		const start = performance.now()540541		// Driver loop handles iterations542		for (let i = 0; i < PROFILING_CONFIG.iterations; i++) {543			scenarioFn()544		}545546		const duration = performance.now() - start547548		completed++549		console.log(550			`[${completed}/${551				PROFILING_CONFIG.scenarios.length552			}] ✓ ${scenarioName} - ${duration.toFixed(2)}ms`553		)554	}555556	console.log()557	console.log("=".repeat(80))558	console.log("Profiling complete!")559	console.log("=".repeat(80))560}561562main()