Alex
Alex

Reputation: 68106

Variable functions definitions inside a loop?

Does defining functions inside a loop affect performance?

Like

var doSomething = function(element){
      $(element).whatever();
    };

return this.each(function(){
  doSomething(this);
})

vs

return this.each(function(){

  var element = this,
      doSomething = function(){
        element.whatever();
      };


  doSomething(); 
  ...
})

In 2nd version the function gets defined like 324532453245 times, depending on how many elements are being iterated, right?

Upvotes: 4

Views: 156

Answers (3)

devstruck
devstruck

Reputation: 1507

Technically, you're defining a defining the functions 80 bajillion times or so in both versions. For high volumes of iteration, you should get some performance benefit from defining it like this.

var doSomething = function(index, element){
      $(element).whatever();
    };

return this.each(doSomething);

Upvotes: 1

Tim Wickstrom
Tim Wickstrom

Reputation: 5701

I would highly recommend using http://jsperf.com/ to test questions like this.

All we will be able to give you is our best educated guess based on our personal experience which will vary widely.

EDIT: Also what doSomething is doing is hugely important in answering this question as well.

I myself have been surprised before by doing testing myself.

Hope this helps.

Upvotes: 2

scibuff
scibuff

Reputation: 13755

well, the scope of element and thus the doSomething is just within the current loop iteration, so if everything is implemented correctly, ie the garbage collector is optimized, it should handle it fine. Of course, you're much better off using the first version.

Upvotes: 1

Related Questions