You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Dispatch耗时是否与Store大小相关?实测验证

Redux dispatch耗时是否与Store大小相关?

我做了一组实验验证Store数据量对dispatch空动作耗时的影响:

  • 空Store时,执行dispatch({ type: "hey" })耗时不足1ms;
  • 当Store存储10万条字符串时,耗时约10ms,且数据量越大耗时越长。

我此前一直认为dispatch耗时与Store大小无关,现在对此产生疑问:Redux的dispatch耗时是否真的取决于Store大小?


组件代码

const dispatch = useAppDispatch();

const [log, setLog] = useState<Array<string>>([]);
const add = (text: string) => {
  setLog([...log, text]);
};

const loadData = async () => {
  add("loading a lot of data to the redux store");

  const newState = [];
  let i;
  for (i = 0; i < 100000; i++) {
    newState.push(i.toString());
  }

  dispatch({ type: "project", payload: { project: newState } });
  add(`data loaded: ${i} strings`);
};

const dummy = async () => {
  add("start dummy dispatch");
  const t0 = performance.now();
  dispatch({ type: "hey" });
  const t1 = performance.now();
  add(`Time it takes to run the function: ${t1 - t0} ms`);
};

const clear = async () => {
  dispatch({ type: "project", payload: { project: [] } });
  setLog([]);
};

return (
  <>
    <div>
      <button onClick={loadData}>Load data</button>
      <button onClick={dummy}>Dispatch empty action</button>
      <button onClick={clear}>Clear</button>
    </div>
    {log.map((l, i) => {
      return <div key={i}>{l}</div>;
    })}
  </>
);

store.ts

import { combineReducers } from "redux";
import {configureStore} from "@reduxjs/toolkit";
import {useDispatch} from "react-redux";
import getProjectReducer from "./reducers/project";

const reducers = combineReducers({
  Project: getProjectReducer
})

export const store = configureStore({
  reducer: reducers,
  devTools: process.env.NODE_ENV !== "production",
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat()
});

export type RootState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;

export const useAppDispatch = () => useDispatch<AppDispatch>();

export default store

reducer

import { createReducer, PayloadAction } from '@reduxjs/toolkit';

const getProjectReducer = createReducer<{project: Array<any>}>({project: []}, {
  'project': (
    state,
    action: PayloadAction<{
      project: any;
    }>
  ) => {
    const {project} = action.payload
    state.project=project;
    return state;
  },
});

export default getProjectReducer;

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:45:29