PHP Optimization, Randomness at work

I stumbled across a piece of code that were acting up, instead of 1048575 possible combinations (0x0 through 0xFFFFF hexadecimal) it varied between 16 distinct combinations … when executed a couple of thousands times in a tight loop.

	public static function generateBase16Code() {
		$chars = "0123456789ABCDEF";
		srand();
		$result = '';
		for ($i = 0; $i < 5; $i++)
			$result .= substr($chars, rand() % strlen($chars), 1);

		return $result;
	}

It produces a string of 5 chars, hexadecimal (0-9 & A-F) in a rather difficult way,

  • Define which characters to use in a string
  • Seed the rand()-function with srand()
  • Prepare a string to store the result in
  • Loop 5 times, where ..
    • A character is chosen from the string, based on "rand() modulo string-length", concatenated to the result-string
  • Return the generated result-string to caller

.. I thought for at few seconds and commented out the above code and replaced it with this;

	public static function generateBase16Code() {
		mt_srand();
		return strtoupper(substr('00000' . dechex(mt_rand(0x0,0xfffff)),-5,5));
	}

.. This could be a one-liner, but I wanted to make sure the random function were seeded properly, therefore two lines of code. The randomness factor is way higher and the function overall is faster, as it doesn’t loop and does string-concatenation only once, instead of at least five times. Also mt_srand() and mt_rand() uses the Mersenne Twister for better randomness, it could be tweaked further with a chosen seed for mt_srand().

2 thoughts on “PHP Optimization, Randomness at work

  1. Hej, det här va helt fel! Det blir inte genomfört EN gång, det blir fler i funktionen som du använder. Back to school!

  2. Magnus: Du var inte vidare specifik om vad du tycker är fel — strängmanipulation är snabbare med de inbyggda funktionerna än att själv loopa, konkatenera ihop strängar. Min snutt producerar dessutom mycket “bättre” slump än original snutten.

    (Att gömma sig bakom en anonymiseringstjänst när man kommenterar på en blog är ju skitseriöst).

Comments are closed.