tes*_*ter 0 javascript performance
如果我从另一个方法多次访问this.something,缓存"this"并访问something()会更快吗?或者我应该反复使用this.something()?
<script type="text/javascript">
var Foo = (function() {
return {
something: function() {
// Do something
},
stuff: function(obj) {
this.something(obj);
// ...
this.something(obj);
/* OR should I cache this? */
var $that = this;
$that.something(obj);
// ...
$that.something(obj);
}
};
}());
</script>
Run Code Online (Sandbox Code Playgroud)
更新:检查CMS的评论下面的真实情况(但我不认为它会改变任何性能).
近似真相:
不,它不会有任何区别.在执行该函数时,创建激活对象并将其放置在函数的作用域链的开头(更具体地,其执行上下文).
激活对象具有属性this,arguments传递的每个参数的一个属性以及函数中声明的每个变量.
因此,this和$that住在同一个范围内,你从中获得什么.当您在本地引用更高范围的对象/值时,您只会得到改进.
+-------------------+ +-------------+
| Execution Context | +->| Scope Chain |
| ----------------- | | | ----------- |
| Scope chain +----+--+ | 0 | +---+----------+
+-------------------+ | 1 | +---+-... |
+-------------+ |
|
|
|
+--------------------+ |
| Activation Object |<--+
| ------------------ |
| this | foo | (if called with foo.method())
| arguments|[someObj]|
| obj | someObj |
| $that | foo | (undefined until assignment)
+--------------------+
Run Code Online (Sandbox Code Playgroud)
从高性能JavaScript中窃取图形.这是一本有趣的书.
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |