Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JavaScript frameworks save core methods for quick reference?

jQuery Example

underscore.js Example

How does that work? How does it make your program faster?

Say I declared var push = ArrayProto.push;

Would the functionality still be the same?

var array = [1, 2, 3];
array.push(4);
//[1, 2, 3, 4];
like image 542
Ryan Avatar asked Aug 09 '26 03:08

Ryan


2 Answers

It's not about speed or performance. Frameworks rarely are. It's about expressiveness of the code you're writing.

When you're using a framework, the idea is generally to write code "the framework's way". To organize and express logic in a way that is consistent and canonical with the style of that framework. This makes it easier to read and understand the code, which in turn makes it easier to share with teams.

In all likelihood, the builders of these frameworks found that they were using these core functions often and that with a simple shortcut to those functions they could streamline the code they were writing a little bit and make the resulting use of the framework more clear for users.

like image 154
David Avatar answered Aug 10 '26 15:08

David


I'm guessing it doesn't really make any difference in performance, as the variable still references the same function, but it does make a difference in minification.

For instance this

Array.prototype.push.apply(array, [value1, value2])

could be minified to

Array.prototype.push.apply(a, [v,k])

so the function and the properties can't really be minified.

If the code uses Array.prototype.push multiple places, like jQuery and Underscore does, using a variable

var push = Array.prototype.push;

Means that anywhere in the code, something like this

Array.prototype.push.apply(array, [value1, value2])

can be minified to just

p.apply(a,[v,k])

which saves a few bytes.

You'll see the same thing with other common variables, for instance

var document  = window.document;

means the library can minify window.document to just d, saving 14 bytes everytime document is used in the code.

like image 23
adeneo Avatar answered Aug 10 '26 17:08

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!