问题
i have read articles that say:
using the
prototype
will be fastest since functions declared are shared. more detail was explained in this article where tapping JS native prototype will increase performance as compared to using 'improvisions'.closures should perform worse since each creation of it returns a separate copy of a set of functions and variables.
objects (functions) are sort of closures but with
this
. has access control (public/private). they're supposed to be better than closures.object literals (the one looking like JSON) act like objects but have no sense of privacy. they are comparable to static methods in JAVA. i have no article to refer, i just included this for comparison.
i was testing a simple comparison of the 4 methods using jsperf in building "Classes" before i proceed with my project and i was looking forward to prototypes winning. however, closures beat them hands down. how come? is there some give and take here? unseen bias?
i may not be new to JS, but i'm totally new to these optimization concepts, please bear with me. i'm still studying about these things.
回答1:
It's not a given that "closures should perform worse". Closures cause each object to get their own copy of the function. But as long as you have enough memory, that shouldn't cause any real performance issues. If anything, closures may even be faster because they don't have to go up the prototype chain to find the property, they are always at the first level right on the object.
The real downside to closures is memory usage, not speed. When creating a ton of objects, it can become a concern.
You also have to consider the runtime in question. Different JavaScript engines will optimize for different situations, depending on what they thought was most important.
回答2:
The difference is that closures are looked up on the scope chain, properties on the internal prototype chain. Even though they are both fundamentally object property lookups (one using activation objects, the other plain Objects), it may simply be that the UAs you've tested are optimised more for one than the other.
P.S. In IE 8, prototypes are faster in the example.
来源:https://stackoverflow.com/questions/9270665/javascript-benchmarks-in-testing-different-emulations-of-a-class