Sign in to follow this  
mazoku

Question on performance

Recommended Posts

Is there any reason to call 

requestAnimationFrame(function() {

loopFunction();

});

and not 

requestAnimationFrame(loopFunction)

Why would anyone choose the first and not the second? 

Share this post


Link to post
Share on other sites

Many callbacks from browser/DOM (such as `requestAnimationFrame`) bind the callback, in the case of `Element.addEventListener` this becomes the Element, in the case of `requestAnimationFrame` it'll be the window. Depending on your use-case this re-binding might be undesirable, e.g. consider the following (I'll use the time honoured OOP/inheritance example of cat speak, particularly relevant given your avatar :) ):

var cat = {
  name: 'mazoku',
  speak: function (str) {
    console.log(this.name, 'says', str)
  }
}

cat.speak('hello')
// mazoku says hello

requestAnimationFrame(cat.speak)
// undefined says 293878273.231

requestAnimationFrame(function () {
  cat.speak('hello')
})
// mazoku says hello

The above highlights 2 possible reasons you'd wrap in a function:

* You don't want the re-binding

* You want to call that function every tick, but supply your own parameters

You can get around the binding issue by ditching OOP-like strategies and just pass plain functions in, however, you'll still want to handle the case of passing variables in, thankfully, JS supports closure and it's a very powerful thing to have at your disposal, and would work great here as one possible solution:

function sayThis (str) {
  return function say () {
    console.log('hello', str)
  }
}

requestAnimationFrame(sayThis('world'))
// hello world

In this case `str` gets locked in the closure, this pattern is sometimes called a thunk, but, really, its just using closure.

Share this post


Link to post
Share on other sites

Benchmark it and see.  I doubt it'll make an observable difference in isolation, and requestAnimationFrame is called quite infrequently when all things are considered.  As Matt says there are valid scoping reasons to wrap functions - and we can always re-reference a pre-wrapped function on subsequent calls (rather than creating a new wrapper function each call).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this