Skip to main content

News

Topic: JS Bind method for your Sphere games (Read 4626 times) previous topic - next topic

0 Members and 1 Guest are viewing this topic.
  • Radnen
  • [*][*][*][*][*]
  • Senior Staff
  • Wise Warrior
JS Bind method for your Sphere games
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).
  • Last Edit: January 16, 2014, 12:53:36 am by Radnen
If you use code to help you code you can use less code to code. Also, I have approximate knowledge of many things.

Sphere-sfml here
Sphere Studio editor here

Re: JS Bind method for your Sphere games
Reply #1
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.
  • Last Edit: January 16, 2014, 11:20:34 pm by alpha123

  • Radnen
  • [*][*][*][*][*]
  • Senior Staff
  • Wise Warrior
Re: JS Bind method for your Sphere games
Reply #2
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.
If you use code to help you code you can use less code to code. Also, I have approximate knowledge of many things.

Sphere-sfml here
Sphere Studio editor here

Re: JS Bind method for your Sphere games
Reply #3
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.