A couple of years ago I posted a class that generats pseudo-random numbers in a repeatable way. This is useful for a variety of tasks, but a recent comment reminded me that I hadn’t tested its performance. Today I’ll pit my repeatable random function against the standard Math.random function as well as Skyboy’s repeatable random class. Read on for the results!

The test class is straightforward. Essentially, I just request a lot of random numbers from each random number generator:

package
{
	import flash.display.*;
	import flash.utils.*;
	import flash.text.*;
 
	public class RandomPerformance extends Sprite
	{
		private var __logger:TextField = new TextField();
		private function row(...cols): void
		{
			__logger.appendText(cols.join(",")+"\n");
		}
 
		public function RandomPerformance()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
 
			var logger:TextField = __logger;
			logger.autoSize = TextFieldAutoSize.LEFT;
			addChild(logger);
 
			var beforeTime:int;
			var afterTime:int;
			var REPS:int = 10000000;
			var i:int;
			var num:Number;
			var jacksonRandom:Random = new Random(33);
			var skyboyRandom:SkyboyRandom = new SkyboyRandom(33);
 
			row("Generator", "Time");
 
			beforeTime = getTimer();
			for (i = 0; i < REPS; ++i)
			{
				num = Math.random();
			}
			afterTime = getTimer();
			row("Math.random", (afterTime-beforeTime));
 
			beforeTime = getTimer();
			for (i = 0; i < REPS; ++i)
			{
				num = skyboyRandom.extractNumber();
			}
			afterTime = getTimer();
			row("Skyboy Random", (afterTime-beforeTime));
 
			beforeTime = getTimer();
			for (i = 0; i < REPS; ++i)
			{
				num = jacksonRandom.nextNumber();
			}
			afterTime = getTimer();
			row("Jackson Random", (afterTime-beforeTime));
		}
	}
}

I ran this test in the following environment:

  • Flex SDK (MXMLC) 4.5.1.21328, compiling in release mode (no debugging or verbose stack traces)
  • Release version of Flash Player 11.1.102.55
  • 2.4 Ghz Intel Core i5
  • Mac OS X 10.7.2

Here are the results I got:

Generator Time
Math.random 278
Skyboy Random 1606
Jackson Random 244

Repeatable Random Performance Chart

Skyboy’s version uses a more sophisticated random technique and as such requires more time to generate its random numbers. In this case the penalty is about a 5x performance loss compared to the other algorithms. Speaking of which, Math.random performs a little slower than my repeatable random class, perhaps due to the static function call. Regardless, if you’re doing a heavy amount of random number generator (e.g. to generate noise), you should be able to get a small speedup by switching from Math.random to my repeatable random number generator. As a bonus, your random numbers will be repeatable!

Spot a bug? Have a suggestion? Post a comment!