-
-
Notifications
You must be signed in to change notification settings - Fork 260
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【每日一题】- 2020-05-14 - 为什么switch/case 的性能要比使用 mapping(对象)好? #127
Comments
贴个benchmark:
代码let count = Math.pow(10, 8)
let swicthCount = count
let objectCount = count
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;
}
}
function authReducerObject(state = authState, action) {
const mapping = {
[LOGIN_SUCCESS]: { ...state, token: action.payload },
[LOGIN_FAILED]: { ...state, error: action.payload }
};
return mapping[action.type] || state;
}
console.time('switch')
while(swicthCount--) {
const action = Math.random() < 0.5 ? LOGIN_SUCCESS : LOGIN_FAILED
authReducer(authState, action)
}
console.timeEnd('switch')
console.time('object')
while(objectCount--) {
const action = Math.random() < 0.5 ? LOGIN_SUCCESS : LOGIN_FAILED
authReducerObject(authState, action)
}
console.timeEnd('object') |
某些浏览器应该对switch做过优化,但是我觉得switch随着case数越来越多,性能肯定会下来,最终应该还是不如mapping,还有一个每次都是创建mapping对象,如果这个对象只初始化一次,也会有所提高 |
简单来说, if else 会自顶向下计算,时间复杂度最坏的情况是 当然这并不是绝对的, switch 的优化方式可以参考这篇文章:https://www.cnblogs.com/182-7167-2685/p/5374111.html |
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
如下代码,是使用了switch case 的redux 的部分代码:
我们将核心代码改成mapping:
实现效果是一样的, 而且代码更简单明了。 通过benchmark测试,我们发现性能switch好很多,这是为什么?
附benchmark图:
The text was updated successfully, but these errors were encountered: