开发者

Is jQuery .live() more memory intensive?

开发者 https://www.devze.com 2023-02-02 17:10 出处:网络
Is jQuery .live() more memory intensive than a sim开发者_如何学编程ple .click() .hover() or .keyup()?

Is jQuery .live() more memory intensive than a sim开发者_如何学编程ple .click() .hover() or .keyup()?

I imagine it would be but to what degree?


I'd guess that it is less memory intensive, but more processor intensive because it only assigns one handler function per event/selector, but it needs to run test for a match against that selector for every event of that type that happens on the page to see if it matches.

In fact, though I haven't dug deep into how it works, I'd imagine that it would need to run test for a match against the selector for every element from the e.target on up to the document (or until it finds a match) to see if anything along the way matches the selector. Someone else can correct me if I'm mistaken.

That said, when you do $('.someClass').click(function() {}), it too only uses the one handler function. So if there are 100 elements with .someClass, they'll all share the same function, but jQuery does need to create a unique entry in jQuery.cache for each element that gets that handler, and as such needs to manage them as though they were separate.

The .delegate() method is a nice compromise between the two.

It behaves the same as .live(), except that you assign it to a local part of the page, so it only processes clicks in that section. Therefore it doesn't need to consider every event that takes place on the page. Rather just those that happen inside that container.


EDIT: Improved phrasing of what the selector engine is doing, with credit to @Šime Vidas.


It depends on what you're trying to accomplish. Just about every case I came across where I used live() ended up being better solved by delegate() anyways. (they are similar, but have a key difference) live() delegates to the root of the entire DOM tree, and checks each and every event that you specify. Using delegate() allows you to specify a different root that watches for events, which ends up performing much more efficiently.

0

精彩评论

暂无评论...
验证码 换一张
取 消