AS3 Math Optimization – Math.random()
February 5th, 2010
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:
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.

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.


February 6th, 2010 at 12:45 pm
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.
June 15th, 2010 at 10:29 am
[...] This post was mentioned on Twitter by . said: [...]