Defining Functions Inline Is Just Fine

I put together this jsperf to see if there’s a difference between defining your function and then using it or defining it inline when looping with jQuery.each. You can try it yourself if you like, but here are the results:

I compared using a pre-defined function with using a function defined inline.

var body = $('body'); // cache this for use with both

//pre-defined
//
var doSomething = function () {
  body.append('<div class=' + this);
}
$.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], doSomething);

// inline
//
$.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], function () {
  body.append('<div class=' + this);
});

Here’s a graph of the results of different browsers performing the test:

Performance of different browsers running $.each with pre-defined and inline functions

Don't take this as an indication of the general performance of the browsers mentioned. Some were run on Linux, some on Mac, one in Wine on Linux, and some in Windows VMs on Linux.

The difference is negligible, so use whichever looks more readable to you. I prefer defining my functions inline, and will now do so with confidence.

This entry was posted in javascript and tagged , , , , . Bookmark the permalink.

One Response to Defining Functions Inline Is Just Fine

  1. Lashell says:

    Bookmarked, I love your site! :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>