Adobe, MAKE SOME NOISE

I was messing around with some bitmap code this evening and I came across a performance bottleneck with some repeated calls to Math.random(). Since I haven't posted anything in a while, I decided to do some benchmarking and try out an alternate (psuedo) random number generator.

I chose the XOR algorithm, primarily because AS3 is lightning-quick with bit operations, and the algorithm is only 4 lines of code. Here are two versions I tried:

  1. // UINT
  2.  
  3. const MAX_RATIO:Number = 1 / uint.MAX_VALUE;
  4. var r:uint = Math.random() * uint.MAX_VALUE;
  5.  
  6. // returns a number from 0 - 1
  7. function XORandom():Number{
  8. r ^= (r << 21);
  9. r ^= (r >>> 35);
  10. r ^= (r << 4);
  11. return (r * MAX_RATIO);
  12. }

  1. // INT
  2.  
  3. const MAX_RATIO:Number = 1 / int.MAX_VALUE;
  4. const NEGA_MAX_RATIO:Number = -MAX_RATIO;
  5. var r:int = Math.random() * int.MAX_VALUE;
  6.  
  7. // returns a number from 0 - 1
  8. // comment out line 13 for -1 - 1
  9. function XORandom():Number{
  10. r ^= (r << 21);
  11. r ^= (r >>> 35);
  12. r ^= (r << 4);
  13. if(r < 0) return r * MAX_RATIO;
  14. return r * NEGA_MAX_RATIO;
  15. }

It's worth noting that this algorithm works from a seed number. For my purposes, picking one random seed and iterating is fine, but this function is predictable enough that you wouldn't want to use this method for crypto or anything where you'd want "very random" data sets. This also could be useful in some situations where you'd want to replay a set of random numbers - such as generating enemies or levels in a game and then creating a replay by saving the seed number.

For my benchmark, I ran 25 sets of 10 million iterations on each function, using the 10.0 release player in Safari.

acctionscript math.random optimization

Interestingly, the logic to gate negative numbers in the signed-int version was enough to push it out quite a bit past the uint version. All told, the uint algorithm runs in just under one fourth the time it takes to call Math.random().

As always, Wikipedia will tell you as much as you want to know about the ins and outs of this algorithm and how it stacks up against other generators. And, just for fun, here's a frequency graph of the output.

Get Adobe Flash player

2 Responses to “AS3 Math Optimization – Math.random()”

  1. makc Says:

    predictable is good, if you need a 100 of levels for a game, it is tempting to generate them automatically, and here is where predictable “random” numbers shine – you just define a level by few “seed” numbers.

    Beeing that lazy, I used small (~1000) array of Math.random() values with offset incremented on every call, and “seed” being initial offset.

  2. Tweets that mention http://www.calypso88.com/?p=524utm_sourcepingback -- Topsy.com Says:

    [...] This post was mentioned on Twitter by . said: [...]

Leave a Reply