Spherical forums

Creations => Programming => Topic started by: Radnen on January 16, 2014, 12:50:59 am

Title: JS Bind method for your Sphere games
Post by: Radnen on January 16, 2014, 12:50:59 am
So, while there are bind methods out there that conform to the ECMA standard, they are far too slow for Sphere. I tested them and this is a 5x faster method.

Code: (javascript) [Select]

// check against existing bind, since TS and SSFML have this for you.
if (!Function.prototype.bind) {
Function.prototype.bind = function(owner, arg1, arg2) {
var m = this;
return function(a1, a2) {
m.call(owner, a1 || arg1, a2 || arg2);
};
}
}


Thoughts, comments? I think for simple bound methods this is good. Yes it doesn't do exactly what bind does, but this is Sphere here, not the internet. So, I'm sure most games will play just fine with this.

It's faster for the two reasons:
1. No pesky Array.prototype.splice.call()'s
2. No "arguments" lookup. It's actually faster to hand-write the args right in. (If you need more than 2 args, just add more).
Title: Re: JS Bind method for your Sphere games
Post by: alpha123 on January 16, 2014, 12:12:55 pm
While it's useful, since it's very far from ECMA compliant, you really shouldn't put it in Function#bind(). That is expected to be ES5-compliant. Maybe make it its own function or something.

Hard coding the arguments in is pretty clever, if very inflexible. arguments is notoriously slow in JS.
Title: Re: JS Bind method for your Sphere games
Post by: Radnen on January 16, 2014, 05:10:15 pm
Sure, I had it as its own function: Delegate. But I had a game with .bind in many, many places (using it to basically re-route 'this'). So it was nice to speed things up a bit by adding that.

But yeah, for a new project, you probably wouldn't want to overwrite bind.
Title: Re: JS Bind method for your Sphere games
Post by: alpha123 on January 16, 2014, 11:20:20 pm
That would be like overwriting Math.floor() with a function that does ~~n. Sure it's faster, but it does something different, albeit similar. I think it would be much better to just grep (or ack, or ag) through the code and replace Function#bind() that way. Or at least less confusing.