1

I am writing a js file that has a lot of jquery commands within the doc-ready part and then a whole swath of functions following it that are referenced in the jquery commands. Here's a short example,

//jquery on ready
$(function() {
  //misc jquery commands
  $('#bzm a').click(function(event) {
        event.preventDefault();
    });
  $('.editable').not('video, img, textarea').click(function(event) { 
        event.stopPropagation();
        loadEditor($(this));
        return false;
    });
});

//bunch of named functions referenced by jquery commands
function loadEditor(node, link){
    event.stopPropagation();

    var value = node.text();

    if (editObj){
        commitEditor(editObj);
    }

    if (node.not('video, img, textarea')){    
        $('#textEdit')
            .copyCSS(node)
            .offset(node.offset())
            .css('display', 'block')
            .val(node.text());

        node.css('color', 'transparent');
    }

    if(node.is('a') || node.parent().is('a') ){

        $('#urlEdit').show();
        $('#urlEdit').val(node.attr('href'));
    } else {$('#urlEdit').hide();}

    editObj = node;

    if (link){
        $('#urlEdit').select();
    }else{
        $('#textEdit').select();
    }
}

I feel like I've seen it said that named functions will cause poor performance in js or something like that.. the closest example I can find is here. I'd just like to know for certain.

Community
  • 1
  • 1
Damon
  • 10,493
  • 16
  • 86
  • 144

1 Answers1

5

No. Calling a named function costs a variable lookup (cheap if not global) and a function call. Passing a named function to another function costs just a variable lookup.

Below are some micro-benchmarks run on Chrome in the square free shell. Take all benchmarks with a grain of salt.

(function () {
  function f() { }
  var a = [1, 2, 3, 4, 5, 6];
  var t0 = Date.now();
  for (var i = 100000; --i >= 0;) { a.map(f); }
  var t1 = Date.now();
  print(t1 - t0);
})() 

24

(function () {
  var a = [1, 2, 3, 4, 5, 6];
  var t0 = Date.now();
  for (var i = 100000; --i >= 0;) { a.map(function f() {}); }
  var t1 = Date.now();
  print(t1 - t0);
})() 

29

Passing the named function is faster than passing the anonymous function possibly because the anonymous function is instantiated repeatedly per loop entry.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • +1 for actually doing the test! Indeed, a micro-optimisation either way; do whatever is more readable. – bobince Sep 05 '11 at 22:52