这里所有的运行时性能测试都忽略了另一个重要考虑因素:网络带宽。
将
$(this)
缓存到本地变量中通常会减小脚本的大小,特别是在缩小后(因为
this
无法从四个字符中减少)。
请考虑:
function hello(text) {
$(this).attr();
$(this).css();
$(this).data();
$(this).click();
$(this).mouseover();
$(this).mouseleave();
$(this).html(text);
}
hello('Hello world');
Closure编译器的压缩输出为:
function hello(a){$(this).attr();$(this).css();$(this).data();$(this).click();$(this).mouseover();$(this).mouseleave();$(this).html(a)}hello("Hello world");
这样可以节省39个字节(20%)。现在考虑以下内容:
function hello(name) {
var $this = $(this);
$this.attr();
$this.css();
$this.data();
$this.click();
$this.mouseover();
$this.mouseleave();
$this.html(name);
}
hello('Hello world');
压缩后的输出是:
function hello(b){var a=$(this);a.attr();a.css();a.data();a.click();a.mouseover();a.mouseleave();a.html(b)}hello("Hello world");
这样做可以节省74字节(37%),几乎将我们的字节节约翻了一番。显然,对于大型脚本的真实世界节约将会更低,但您仍然可以通过缓存来显著减少脚本的大小。
实际上,只有缓存$(this)
会使得利润更大。您可以获得微小但可测量的运行时性能提升。更重要的是,您可以减少在网络传输中的字节数,并且这直接转化为更多的收益,因为页面加载速度越快,销售额就越高。
从这个角度看,您实际上可以说对于反复使用$(this)
而不进行缓存存在着可量化的成本。
$(this).addClass('fooClass').attr('data-bar', "bar").css('background-color', 'red');
- Jose Rui Santos