Memoize

This is a memoize function that you can use to make programs with lookup functions run faster.

Code

	$MEMOIZATION_LIMIT = 100; // The maximum size of each memory array.
	$MEM_VALS = array(); // The memory arrays.
	function memoize($array, $key, $value=null)
	{
		global $MEM_VALS, $MEMOIZATION_LIMIT;
		$key = "V".$key; // Fix to allow integer keys without auto-indexing.
		if(!isset($MEM_VALS[$array]))
			$MEM_VALS[$array] = array();
		if($value != null)
		{
			$MEM_VALS[$array][$key] = $value;
			if(sizeof($MEM_VALS[$array]) > $MEMOIZATION_LIMIT)
			array_shift($MEM_VALS[$array]);
		}
		if(isset($MEM_VALS[$array][$key]))
			return $MEM_VALS[$array][$key];
		return null;
	}

	

Description

Memoization is, in my opinion, a stupid term for remembering values recently requested from a lookup function. This function will make it very easy to add a memoization shortcut to your own lookup functions. You will get higher overall speed from your program at a cost of memory usage.

Usage

The following function makes use of the memoization function. The first two and the last lines of the code are all that are added to give it full memoization ability.

	function get_name_from_ssn($ssn)
	{
		$name = memoize("ssn_name", $ssn); // See if SSN-Name map is in memory
		if($name != null) return $name; // If it is, return it
		$result = db_query("select name from users where ssn='$ssn'");
		$row = db_fetch_object($result);
		$name = $row->ssn;
		return memoize("ssn_name", $ssn, $name); // Save SSN-Name map to memory
	}
	

How Does It Work?

Each function that uses the memoize function uses a unique name (such as the "ssn_name" string above). Memoize will create a memory array for the string. If both a key and value are given, memoize will save that value to the key and then return the value. If only a key is given, the value for the key is given (or null if the key is not set). Memoize automatically trims the memory if it gets too big. This will allow you to control memory usage.