Let’s say that we have a PC with unlimited processing power, BUT with very little RAM. We need to optimize its memory, by using a script that creates 2 functions: one for archiving an array and another one to search through this array.
There are also a set of rules that you need to respect:
1: You will use only Php Coding
2: You can modify only these 2 functions
3: You will not use apps like: Memcached, apc, files, alt thread…
4: Don’t cheat.
5: You can reply to this article with all new records that you achieve.
You are given the following:
function getMem() {
$mem = memory_get_usage(true) / 1024;
return $mem;
}
$array = range(1,1000000);
shuffle($array);
$mem = getMem();
$string = compress($array);
echo 'You used : ',getMem() - $mem,' Kb',PHP_EOL;
function compress($array){
/** TODO create a compress function**/
return implode(',',$array);
}
function get($nr,$string) {
/** TODO create get function**/
$x = explode(',',$string);
return $x[$nr];
}
for($i = 0;$i <100; $i++) {
$test = rand(0,1000000-1);
if($array[$test] != get($test,$string)) {
try {
throw New Exception('You failed!!!');
} catch(Exception $e) {
echo $e->getMessage();die;
}
}
}
echo 'You Win',PHP_EOL;
echo date('Y-m-d H:i:s'),PHP_EOL;
So… What’s your best memory consumption result?
This test was proposed by Alin, Team Leader @ INNOBYTE.