拥有状态和使用函数获取状态之间的性能差异是什么?



仅为例如,让我们看看我们有三个事件侦听器mousemovekeydownkeyup。我们想记录space密钥和当前鼠标位置。

import getState from "../state";
  //version one, the variable is in place and gets mutated if changes
let spacePressed = false;
window.addEventListener("mousemove", (x, y) => {
  if (spacePressed) doSomethingWithMousePos(x, y);
});
  //version two, the variable is in a state outside
window.addEventListener("mousemove", (x, y) => {
  const { spacePressed } = getState();
  if (spacePressed) doSomethingWithMousePos(x, y);
});
//...
window.addEventListener("keydown", functionWhichSetsSpacePressed);
window.addEventListener("keyup", functionWhichSetsSpacePressed);

只是为了澄清它与反应或redux无关。示例很好,因为mousemove经常发生,因此即使很小的性能差异也很重要。那么,拥有状态到位,该功能只需要读取它,而将状态放在外部文件中,该功能可以在函数传递状态本身的情况下有什么区别?(这样的东西:

const state = {};
export const getState = () => state;

(

首先要提及的是,在前端JavaScript中优化这些东西几乎没有用,因为这里的主要瓶颈是DOM操作和DOM渲染。但是,如果您真的很感兴趣,我不会回答更快的速度和较慢的内容,我将发布一种使用benchmark.js轻松测量这些事情的方法。

var suite = new Benchmark.Suite();
const state = {};
const getState = () => state;
// add tests
suite.add('Get State', function() {
  getState()['foo'] = 'bar';
})
.add('Read state', function() {
  state.foo = 'bar';
}).on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
}).run({'async': true});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js" ></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js" ></script>
</body>
</html>

最新更新