jeudi 26 novembre 2015

JS patterns with closures and performance

I have a doubt about JS patterns and performance, after read "Javascript: The good parts" by Douglas Crockford you an idea of how Closures works, the first in mind it's to write code like this

(function(){
    "use strict";

    var OpenSloth = {};

    OpenSloth.someFunction = function () {...};

    OpenSloth.someOtherFunction = function () {...};

    window.OpenSloth;
})();

But I read latter a book named "High Performance Javascript" by Nicholas C. Zakas (Also O'Reilly) and they say from the page 24 to 25:

Closures are one of the most powerful aspects of Javascript, allowing a function to access data outside of its local scope. The use of cloasures has been popularized through the writings of Douglas Crockford and is now ubiquitous in most complex web aplications. There is, however, a performance impact associated with using cloasures...

...Since the closure's [[Scope]] property cointains references to the same objects as the execution context's scope chain, there is a side effect. Typically, a function's activation object is destroyed when the execution context is destroyed. When there's a cloasure involved, through, the activation object isn't destroyed, because a reference still exists in the closure's [[Scope]] property. This means that cloasures require more memory overhead in a script than a nonclosure function...

High Performance JavaScript, by Nicholas C/ Zakas. Copyright 2010 Yahoo!, Inc, 978-0-596-80279-0."

After that I want to reduce closures as far as I can, then I came up with this solution:

var OpenSloth = {};

OpenSloth._someFunction = function () {
    "use strict";

    ...
};

OpenSloth._someOtherFunction = function () {
    "use strict";

    ...
};

But I want to know whats the conventions about it, I'm writing bad code with this second option? and why? it is an anti-pattern?

Thanks for your time.

Aucun commentaire:

Enregistrer un commentaire