这里所有运行时性能测试都遗漏的一件事是另一个主要考虑因素:
网络带宽。
缓存$(this)到局部变量通常会减小脚本的大小,尤其是在缩小时(因为this不能从四个字符减少)。
考虑:
function hello(text) {
$(this).attr();
$(this).css();
$(this).data();
$(this).click();
$(this).mouseover();
$(this).mouseleave();
$(this).html(text);
}
hello('Hello world');
关闭编译器的缩小输出是
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)。