File size: 9,061 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import type { PayloadAction } from '@reduxjs/toolkit'
import { configureStore, createSlice } from '@reduxjs/toolkit'
import {
  unstable_autotrackMemoize as autotrackMemoize,
  createSelectorCreator,
  lruMemoize,
  weakMapMemoize
} from 'reselect'
import { vi } from 'vitest'

describe('More perf comparisons', () => {
  const originalEnv = process.env.NODE_ENV

  beforeAll(() => {
    process.env.NODE_ENV = 'production'
  })
  afterAll(() => {
    process.env.NODE_NV = originalEnv
  })

  const csDefault = createSelectorCreator(lruMemoize)
  const csAutotrack = createSelectorCreator(autotrackMemoize)

  interface Todo {
    id: number
    name: string
    completed: boolean
  }

  type TodosState = Todo[]

  const counterSlice = createSlice({
    name: 'counters',
    initialState: {
      deeply: {
        nested: {
          really: {
            deeply: {
              nested: {
                c1: { value: 0 }
              }
            }
          }
        }
      },

      c2: { value: 0 }
    },
    reducers: {
      increment1(state) {
        // state.c1.value++
        state.deeply.nested.really.deeply.nested.c1.value++
      },
      increment2(state) {
        state.c2.value++
      }
    }
  })

  const todosSlice = createSlice({
    name: 'todos',
    initialState: [
      { id: 0, name: 'a', completed: false },
      { id: 1, name: 'b', completed: false },
      { id: 2, name: 'c', completed: false }
    ] as TodosState,
    reducers: {
      toggleCompleted(state, action: PayloadAction<number>) {
        const todo = state.find(todo => todo.id === action.payload)
        if (todo) {
          todo.completed = !todo.completed
        }
      },
      setName(state) {
        state[1].name = 'd'
      }
    }
  })

  const store = configureStore({
    reducer: {
      counter: counterSlice.reducer,
      todos: todosSlice.reducer
    },
    middleware: gDM =>
      gDM({
        serializableCheck: false,
        immutableCheck: false
      })
  })

  type RootState = ReturnType<typeof store.getState>

  const states: RootState[] = []

  for (let i = 0; i < 10000; i++) {
    states.push(store.getState())
    store.dispatch(counterSlice.actions.increment1())
    states.push(store.getState())
    store.dispatch(counterSlice.actions.increment2())
    states.push(store.getState())
    store.dispatch(todosSlice.actions.toggleCompleted(1))
    states.push(store.getState())
    store.dispatch(todosSlice.actions.setName())
    states.push(store.getState())
  }

  it('More detailed perf comparison', () => {
    const cdCounters1 = csDefault(
      (state: RootState) =>
        state.counter.deeply.nested.really.deeply.nested.c1.value,
      (state: RootState) => state.counter.c2.value,
      (c1, c2) => {
        return c1 + c2
      }
    )

    const cdCounters2 = csDefault(
      (state: RootState) => state.counter.deeply.nested.really.deeply.nested.c1,
      (state: RootState) => state.counter.c2,
      (c1, c2) => {
        return c1.value + c2.value
      }
    )

    const cdTodoIds = csDefault(
      (state: RootState) => state.todos,
      todos => {
        return todos.map(todo => todo.id)
      }
    )

    const cdTodoIdsAndNames = csDefault(
      (state: RootState) => state.todos,
      todos => {
        return todos.map(todo => ({ id: todo.id, name: todo.name }))
      }
    )

    const cdCompletedTodos = csDefault(
      (state: RootState) => state.todos,
      todos => {
        const completed = todos.filter(todo => todo.completed)
        return completed.length
      }
    )

    const cdCompletedTodos2 = csDefault(
      (state: RootState) => state.todos,
      todos => {
        const completed = todos.filter(todo => todo.completed)
        return completed.length
      }
    )

    const caCounters1 = csDefault(
      (state: RootState) =>
        state.counter.deeply.nested.really.deeply.nested.c1.value,
      (state: RootState) => state.counter.c2.value,
      (c1, c2) => {
        return c1 + c2
      }
    )

    const caCounters2 = csAutotrack(
      (state: RootState) => state.counter.deeply.nested.really.deeply.nested.c1,
      (state: RootState) => state.counter.c2,
      (c1, c2) => {
        // console.log('inside caCounters2: ', { c1, c2 })
        return c1.value + c2.value
      }
    )

    const caTodoIds = csAutotrack(
      (state: RootState) => state.todos,
      todos => {
        return todos.map(todo => todo.id)
      }
    )

    const caTodoIdsAndNames = csAutotrack(
      (state: RootState) => state.todos,
      todos => {
        return todos.map(todo => ({ id: todo.id, name: todo.name }))
      }
    )

    const caCompletedTodos = csAutotrack(
      (state: RootState) => state.todos,
      todos => {
        const completed = todos.filter(todo => todo.completed)
        return completed.length
      }
    )

    const caCompletedTodos2 = csAutotrack(
      (state: RootState) => state.todos,
      todos => {
        const completed = todos.filter(todo => todo.completed)
        return completed.length
      }
    )

    const defaultStart = performance.now()
    for (const state of states) {
      cdCounters1(state)
      cdCounters2(state)
      // console.log('csCounters2', cdCounters2(state))
      cdTodoIds(state)
      cdTodoIdsAndNames(state)
      cdCompletedTodos(state)
      cdCompletedTodos2(state)
    }
    const defaultEnd = performance.now()

    const autotrackStart = performance.now()
    for (const state of states) {
      caCounters1(state)
      caCounters2(state)
      // console.log('State.counter: ', state.counter)
      // console.log('caCounters2', caCounters2(state))
      caTodoIds(state)
      caTodoIdsAndNames(state)
      caCompletedTodos(state)
      caCompletedTodos2(state)
    }
    const autotrackEnd = performance.now()

    const allSelectors = {
      cdCounters1,
      cdCounters2,
      cdTodoIds,
      cdTodoIdsAndNames,
      cdCompletedTodos,
      cdCompletedTodos2,
      caCounters1,
      caCounters2,
      caTodoIds,
      caTodoIdsAndNames,
      caCompletedTodos,
      caCompletedTodos2
    }

    // console.log('\nTotal recomputations:')
    // Object.entries(allSelectors).forEach(([name, selector]) => {
    //   console.log(name, selector.recomputations())
    // })

    // console.log('Total elapsed times: ', {
    //   defaultElapsed: defaultEnd - defaultStart,
    //   autotrackElapsed: autotrackEnd - autotrackStart
    // })
  })

  it.skip('weakMapMemoizer recalcs', () => {
    const state1 = store.getState()

    store.dispatch(counterSlice.actions.increment1())
    const state2 = store.getState()

    const csWeakmap = createSelectorCreator(weakMapMemoize)

    const cwCounters2 = csWeakmap(
      (state: RootState) => state.counter.deeply.nested.really.deeply.nested.c1,
      (state: RootState) => state.counter.c2,
      (c1, c2) => {
        // console.log('inside caCounters2: ', { c1, c2 })
        return c1.value + c2.value
      }
    )

    for (let i = 0; i < 10; i++) {
      cwCounters2(state1)
      cwCounters2(state2)
    }

    console.log('cwCounters2.recomputations()', cwCounters2.recomputations())
  })

  test('Weakmap memoizer has an infinite cache size', async () => {
    const fn = vi.fn()

    let resolve: () => void
    const promise = new Promise<void>(r => (resolve = r))

    const registry = new FinalizationRegistry(heldValue => {
      resolve()
      fn(heldValue)
    })

    const createSelectorWeakmap = createSelectorCreator(weakMapMemoize)

    const store = configureStore({
      reducer: {
        counter: counterSlice.reducer,
        todos: todosSlice.reducer
      },
      middleware: gDM =>
        gDM({
          serializableCheck: false,
          immutableCheck: false
        })
    })

    const reduxStates: RootState[] = []

    const NUM_ITEMS = 10

    for (let i = 0; i < NUM_ITEMS; i++) {
      store.dispatch(todosSlice.actions.toggleCompleted(1))
      const state = store.getState()
      reduxStates.push(state)
      registry.register(state, i)
    }

    const cdTodoIdsAndNames = createSelectorWeakmap(
      (state: RootState) => state.todos,
      todos => {
        // console.log('Recalculating todo IDs')
        return todos.map(todo => ({ id: todo.id, name: todo.name }))
      }
    )

    for (const state of reduxStates) {
      cdTodoIdsAndNames(state)
    }

    expect(cdTodoIdsAndNames.recomputations()).toBe(NUM_ITEMS)

    for (const state of reduxStates) {
      cdTodoIdsAndNames(state)
    }

    expect(cdTodoIdsAndNames.recomputations()).toBe(NUM_ITEMS)

    cdTodoIdsAndNames.memoizedResultFunc.clearCache()

    cdTodoIdsAndNames(reduxStates[0])

    expect(cdTodoIdsAndNames.recomputations()).toBe(NUM_ITEMS)

    cdTodoIdsAndNames(reduxStates[1])

    expect(cdTodoIdsAndNames.recomputations()).toBe(NUM_ITEMS)

    // @ts-ignore
    reduxStates[0] = null
    if (global.gc) {
      global.gc()
    } else {
      return
    }

    await promise
    expect(fn).toHaveBeenCalledWith(0)

    // garbage-collected for ID: 3
  })
})