Javascript - 使用local var或this?

use*_*995 2 javascript caching this keyword

我正在使用原型方法,这里是scenerio

function Foo () {
    this.x = 5;
    this.y = 2;
    this.z = this.addValues();
}
Foo.prototype = {
    addValues:  function (){
        return this.x + this.y; 
    }
}
Run Code Online (Sandbox Code Playgroud)

显然这只是一个简单的例子; 在实际项目中,'addValue'函数中会有很多活动.使用'this'关键字100次或将其缓存到局部变量可以帮助任何性能改进.例如,下面会有什么区别?

Foo.prototype = {
    addValues:  function (){
        var self = this;
        return self.x + self.y; 
    }
}
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

self.x和之间可能没有任何有意义的区别this.x.什么可能有所作为是

  var x = this.x, y = this.y;

  // massive amounts of computation involving x and y
Run Code Online (Sandbox Code Playgroud)

除非你真的参与一些前沿的游戏开发或其他什么,否则这种微观优化可能不值得.首先获取你的算法数据结构,然后再担心这样的事情.您永远不知道JavaScript运行时系统的开发人员何时会引入新的优化.他们无法修复您的错误算法,但它们可以显着影响微优化.