qkreltms / react-action-listener

Middleware, React hook which allows making side effect and listening actions of Context or Redux
MIT License
8 stars 0 forks source link

feat: improve performance by using Map instead of object #47

Closed qkreltms closed 3 years ago

qkreltms commented 3 years ago

Is your feature request related to a problem? Please describe. You can improve performance by using Map instead of object when adding, reading listeners.

cnt 100 1000 100000
type Map Object Map Object Map Object
func set read set read set read set read set read set read
score(ms) 0.67 0.38 0.69 0.44 2.47 0.89 3.78 1.19 228 39 374 179
0.5 0.4 0.76 0.47 2.44 0.34 3.82 1.22 247 37 371 151
0.51 0.37 0.69 0.43 2.43 0.94 3.82 1.52 238 47 342 147
0.54 0.41 0.71 0.42 3.76 0.88 4.13 1.18 234 50 354 150
0.62 0.38 0.73 0.45 2.53 0.84 3.84 1.16 253 48 369 142
avg(ms) 0.56 0.38 0.71 0.44 2.72 0.77 3.87 1.25 240 44.2 362 153.8

Test scripts

Object

test('performance', () =>{
    const listenMiddleware = createMiddleware();

    let cnt = 0;
    console.time()
    for (let i=0;i<100;i++) {
      listenMiddleware.addListener('TEST', () => {
        cnt += 1;
      });
    }
    console.timeEnd()
    console.time()
    const middleware = listenMiddleware(mockStore)(mockNext);
    middleware({ type: 'TEST' });
    console.timeEnd()
    expect(Object.keys(listenMiddleware.listeners).length).toBe(100);
    expect(cnt).toBe(100);
})

Map

test('performance', () => {
  const listenMiddleware = createMiddleware();

  let cnt = 0;
  let t0 = performance.now()
  for (let i=0;i<100;i++) {
    listenMiddleware.addListener('TEST', () => {
      cnt += 1;
    });
  }
  let t1 = performance.now()
  console.log(t1-t0)
  t0 = performance.now()
  const middleware = listenMiddleware(mockStore)(mockNext);
  middleware({ type: 'TEST' });
  t1 = performance.now()
  console.log(t1-t0)
  expect(listenMiddleware.listeners.size).toBe(100);
  expect(cnt).toBe(100);
});