Skip to content

【每日一题】- 2020-05-14 - 为什么switch/case 的性能要比使用 mapping(对象)好? #127

@azl397985856

Description

@azl397985856

如下代码,是使用了switch case 的redux 的部分代码:

const LOGIN_SUCCESS = "LOGIN_SUCCESS";
const LOGIN_FAILED = "LOGIN_FAILED";

const authState = {
  token: "",
  error: "",
};

function authReducer(state = authState, action) {
  switch (action.type) {
    case LOGIN_SUCCESS:
      return { ...state, token: action.payload };
    case LOGIN_FAILED:
      return { ...state, error: action.payload };
    default:
      return state;
  }
}

我们将核心代码改成mapping:

function authReducer(state = authState, action) {
  const mapping = {
    [LOGIN_SUCCESS]: { ...state, token: action.payload },
    [LOGIN_FAILED]: { ...state, error: action.payload }
  };

  return mapping[action.type] || state;
}

实现效果是一样的, 而且代码更简单明了。 通过benchmark测试,我们发现性能switch好很多,这是为什么?

附benchmark图:

Switch Mapping
43.033 71.609
40.247 64.800
37.814 66.123
37.967 63.871
37.616 68.133
38.534 69.483
37.261 67.353
41.662 66.113
38.867 65.872
37.602 66.873

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions