cdmckay
cdmckay

Reputation: 32260

Where should I define my Javascript closure?

I'm creating my own JavaScript Array-like object and I have methods that call closures. I was just wondering where was the most efficient place to define a closure.

For example, imagine I have a map function and a chop function:

MyObject.prototype = 
{
  map: function(fn) { ... applies fn to each element ... };

  chop: function() 
  { this.map( 
    function(element) 
    {
      ... chop off last character ... 
    } 
  )};
}

Is it more efficient to do this instead?

MyObject.prototype = 
{
  map: function(fn) { ... applies fn to each element ... };

  __chop: function(element) 
  {
    ... chop off last character ... 
  }

  chop: function() 
  { this.map(this.__chop) };
}

Upvotes: 0

Views: 502

Answers (4)

Drew
Drew

Reputation: 4691

Trading a function closure, for another function closure doesn't lead to a more efficient code. The most memory efficient one would be one that does not use closures at all.

__proto__ = {
  map: function(){},
  _chop: function(str){
    return str.slice( str.length, -1 );
  },
  chop: function(arr){ 
    this.map(this._chop, arr);
  }
}

This question rates very high on google for "closure memory usage", I don't think it qualifies. This is a problem that is difficult to diagnose though.

The answer here is more an example of hiding functionality within a closure, but it adds the cost of maintaining that memory space to store those private variables.

Upvotes: 0

Christoph
Christoph

Reputation: 169613

The second one is more efficient. This

  chop: function() 
  { map( 
    function(element) 
    {
      ... chop off last character ... 
    } 
  )}

will create a new function object on each call to chop() with the respective runtime and memory overhead. As there won't be any lingering references to the new object, it can be immediately gargage collected, but it's still bad practice to create more objects than necessary.

I'd suggest the following pattern:

MyObject.prototype = (function() {

    function map(fn) { ... }

    function chopElement(element) { ... }

    function chop() {
        this.map(chopElement);
    }

    return {
        map : map,
        chop : chop
    };

})();

Upvotes: 5

Allain Lalonde
Allain Lalonde

Reputation: 93348

Neither creating the function, nor looking it up are costly operations in JavaScript, so if you have an "array" with a decent # of elements in it, the difference between either method will be negligible.

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351536

They are effectively the same thing - go with whichever one is more readable. For what its worth I prefer the second one.

Upvotes: 0

Related Questions