简体   繁体   English

缓存$(这个)是否有性能提升?

[英]Is there a performance gain from caching $(this)?

I often use $(this) inside jQuery event handlers and never cache it. 我经常在jQuery事件处理程序中使用$(this)并且永远不会缓存它。 If I'll do 如果我愿意的话

var $this = $(this);

and will use variable instead of the constructor, will my code get any significant extra performance? 并将使用变量而不是构造函数,我的代码将获得任何显着的额外性能?


JS Perf test to measure the performance gain from this optimization: http://jsperf.com/jquery-this-caching JS Perf测试用于衡量此优化的性能增益: http//jsperf.com/jquery-this-caching

A teeny tiny miniscule imperceptible one , yes. 这是一个微不足道的微小的微小的 ,是的。 Significant? 重大? No. 没有。

Every time you do $(this) , it results in several function calls and a couple of memory allocations. 每次执行$(this) ,都会导致多个函数调用和几个内存分配。 The function calls are neither here nor there (even on IE6, I was surprised to learn ), but the memory churn could add up on browsers that don't handle memory management very well. 函数调用既不在这里也不在那里(即使在IE6上,我也很惊讶地学习 ),但内存流失可能会增加不能很好地处理内存管理的浏览器。 Most modern ones do. 大多数现代的。

I always save the result to a variable, because I just don't like calling functions and allocating objects needlessly. 我总是将结果保存到变量中,因为我不喜欢调用函数和不必要地分配对象。 And it saves typing those parens. 它可以节省那些parens的输入。 :-) :-)

Yes, because everytime you do $(this) you create a new jquery object. 是的,因为每次你执行$(this)都会创建一个新的jquery对象。
But you won't get a significant performance, just if you do it more than 1000x 但是,如果你的表现超过1000倍,你将无法获得重要的表现

And it's a good practice to cache objects used more than once. 并且缓存多次使用的对象是一种很好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM