continue
I have two scenerios. In each scenerio, tell me which version of doing the same exact thing is more efficient (e.g. uses less CPU or memory):
First scenerio:
/*version 1*/
$('body').append('#something');
/*version 2*/
$('#something').insertAfter('body > *:last-child');
Second scenerio:
/*version 1*/
$('#something').method1();
$('#something').method2();
$('#something').method3();
/*version 2*/
var $reference = $('#something');
$reference.method1();
$reference.method2();
$reference.method3();
So in each scenerio, which version is more efficient?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在第一种情况下,第一种情况更有效,因为
$("#someid")
最终相当于对本机代码的调用document.getElementById
调用。与类选择器相比,ID 选择器相当便宜。对$('body > *:last-child')
的调用将是对 SizzleJS 的更复杂的调用。在第二种情况下,第二种情况更有效,因为您可以避免对
document.getElementById
进行额外的两次调用,而只需预先声明您的对象。In the first scenario the first is more efficent since
$("#someid")
ultimatly amounts to adocument.getElementById
call which is a call to native code. Id selectors are fairly cheap compared to class selectors. A call to$('body > *:last-child')
is going to going to be a much more complex call to SizzleJS.In the second scenario the second is more efficient since you avoid making an additional two calls to
document.getElementById
and just declare your object up front.这可能不是您正在寻找的答案,但是......
从总体上看,差异几乎无法衡量,因此并不重要。只需专注于编写干净、简单且易于维护的代码即可。
This may not be the answer you're looking for, but...
In the grand scheme of things, the difference is going to be so barely measurable that it doesn't really matter. Just focus on writing clean, simple and easily maintainable code.
除非你打算重用该对象,否则
unless you plan to reuse the object, then do