Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.proxy vs. underscore.bind

In the context of using methods as event handlers (i.e. $(...).on('something', myObject.handleSomething)). I discovered the relatively large performance difference between $.proxy and _.bind (http://jsperf.com/bind-vs-jquery-proxy/27) and looked at their implementation.

jQuery (http://james.padolsey.com/jquery/#v=1.10.2&fn=proxy) ends up returning:

args = core_slice.call(arguments, 2);
proxy = function () {
    return fn.apply(context || this, args.concat(core_slice.call(arguments)));
};

while underscore (http://underscorejs.org/docs/underscore.html#section-60) ends up returning (ctor is var ctor = function(){};):

args = slice.call(arguments, 2);
return bound = function() {
  if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
  ctor.prototype = func.prototype;
  var self = new ctor;
  ctor.prototype = null;
  var result = func.apply(self, args.concat(slice.call(arguments)));
  if (Object(result) === result) return result;
  return self;
};

I understand that _.bind will allow me to bind arguments for a new call, but will it have any practical advantage if I only want to use myObject.handleSomething as an event handler?

Is it possible to write something similar to _.bindAll using $.proxy? E.g.

$.proxyAll = function (obj) {
    for (var attr in obj) if (obj.hasOwnProperty(attr) && $.isFunction(obj[attr])) {
        obj[attr] = $.proxy(obj[attr], obj);
    }
    return obj;
};
like image 233
thebjorn Avatar asked Sep 27 '13 16:09

thebjorn


1 Answers

Are you sure you're measuring the performance you care about?

Seems your test case is measuring the performance of binding the function, whereas this test case measures the performance of the bound function: http://jsperf.com/bind-vs-jquery-proxy/38

You should only be binding functions a finite (and relatively small) number of times, so performance wouldn't really matter. It was a surprise to me, but measuring the performance of the bound function seems to flip the results.

Also, note that your original test results varied across browsers.

like image 65
colllin Avatar answered Nov 01 '22 03:11

colllin