0

Is it ok regarding performance and efficiency to declare a function inside a function that is called on each AnimationFrame? Is A) as ok as B) ?

A)

function update() {
 function do () { ...}
}

B)

function update() {
 do();
}
 function do () { ...}
asked Mar 31, 2015 at 15:48
3
  • 2
    Why would you declare the function on every frame? Commented Mar 31, 2015 at 15:49
  • just to closure, what belongs together, sharing same varibales Commented Mar 31, 2015 at 15:51
  • A and B do not act the same. Commented Mar 31, 2015 at 15:54

2 Answers 2

2

No, it's not a good idea because you're making it redeclare the same function over and over.

A better pattern would be:

(function() { // this is your closure
 var genericVariableOne = 123,
 genericVariableTwo = 456;
 function genericFunctionOne() {...}
 // now do stuff here
})();

This way you are only declaring functions once within the closure. For variables, declaring them outside may or may not be a good idea depending on how they are used.

answered Mar 31, 2015 at 15:54
Sign up to request clarification or add additional context in comments.

Comments

1

Yes - it is ok to declare functions inside functions and in fact desirable in many situations. They are called closures. All major JavaScript APIs depend on this concept heavily from jQuery, to AngularJS to Dojo. Older versions of MSIE discouraged it's use but all modern browsers use JavaScript engines that are very efficient and can give you good performance with closures.

answered Mar 31, 2015 at 15:53

2 Comments

"Okay" and performant are two completely different things here.
Closures block garbage collection of their entire scope chain for the life of the closure. Function binding or refactoring is a much better solution.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.