josephg / Chipmunk-js

Port of slembcke/Chipmunk-Physics to Javascript
http://dl.dropbox.com/u/2494815/demo/Joints.html
536 stars 59 forks source link

Possible optimization: Array-based vectors #10

Closed ghost closed 11 years ago

ghost commented 11 years ago

Why? When I was looking for a better 3D matrix lib a few months ago, glMatrix was the all-around winner in these benchmarks. Apparently using Arrays instead of Objects is a big win in JS. Vectors in chipmunk-js currently aren't very OO-like, so this change might be reasonable...

Pros: faster! (and less cumbersome IMHO)

Cons: unlike Chipmunk-C conventions; requires 146 changes; will break any code that manipulates .x/.y

I might be willing to try this in my fork. Any thoughts?

nornagon commented 11 years ago

I ran that benchmark on this machine (ubuntu with a crappy gfx driver, but fast cpu and lots of ram) and closure was the clear winner except for rotation (where TDL did better) and transpose (where CanvasMatrix did better).

So if you make this change, be sure to test it very well, since I think it'd be a pretty big drop in readability.

josephg commented 11 years ago

glMatrix doesn't just use arrays. It uses typed arrays (Float32Array).

When I ported cpVect I did some simple benchmarks on jsperf to try and pick the right data structure for vectors - IIRC it wasn't really any faster using arrays. But there's no need to speculate. Hop on jsperf.com and run the experiment.

josephg commented 11 years ago

Oh, and there was a decent (~20% iirc) speedup from making a lot of the 'hot' vectors inline (body.vx, body.vy) instead of body.v.x and body.v.y. They're faster to access and you put less load on the GC. Because javascript is duck typed, you can just pass the body in directly to any of the vector functions.

If we swap to arrays, we lose that little optimization.

ghost commented 11 years ago

Oh, interesting... in Firefox (x86-64) glMatrix wins and the others yield a lot of 'bad' results, but it stinks in Android Firefox 16-beta (which does support typed arrays). Closure and tdl.fast have a slight edge in Chrome; all three are Google's, surprise surprise. All those matrix libs except glMatrix are 2x-10x faster in Chrome, too. Google's engineers probably figured out how to make regular arrays as fast as typed arrays, just within the past year.

Thanks for the feedback.. glad I asked. I'll close this issue now :)