4

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?

1
  • 1
    Right. I'd use the first version. Commented Mar 29, 2012 at 16:26

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.