Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed of the Math Object in Javascript

Tags:

javascript

I'm working on a javascript application that makes intensive use of math operations, dozens of calls per mouse move. I've been working on others' people code as a starting point, and I often find work arounds for the native javascript Math, such as...

var pi = Math.PI
var distance = (x * x) + (y * y) / R * R
var pixels = ~~(x/y)

Is there a significant performance hit for using the Math object? If so, what are some common workarounds?

like image 567
methodofaction Avatar asked Jan 16 '12 19:01

methodofaction


1 Answers

If you are for some reason doing computing intensive stuff in javascript, you must remember those things (*and read David Mandelin's Know Your Engines: How to Make Your JavaScript Fast presentation - PDF, where he describes this in more details*):

  1. inline everything you can.

  2. function calls are very expensive

  3. object access is expensive

  4. polymorphism can cost you performance, your variables and arguments should always hold only one data type.

Math object is not especially slow, but you will not find distance() function there anyway, and accessing its methods from closure via Math.method() calls is, inefficient.

so sqrt is, of course, worse than x*x, custom random function might be better for you, Pi should be cached in loops, min and max should probably be avoided as well, no idea about trigonometry and logarithms speed.


P.S.: You can do things like ((x >= 0 ? x : -x) + 0.5) >> 0, to replace Math.ceil(Math.abs()), but remember - when i say "intensive" - i'm talking about number crunching, data processing, physics, graphics and things like that. For normal JavaScript sites or RIAs - you should not do stuff i am suggesting here. Also, most of the speed hacks have their side effects

like image 153
c69 Avatar answered Sep 20 '22 22:09

c69