Jump to content

Question on performance


mazoku
 Share

Recommended Posts

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.

Link to comment
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).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...