I am trying to find a way to map big amount of strings to ints. I tried it using arrays and found a behaviour that I don't understand. When I index arrays by strings (array('someStirng' => 1)) it consumes less memory than vice versa (array(1 => 'someString')). Does it mean, that it's better to index arrays by strings and leave ints as values for big amount of string-int pairs or what's the catch? Why there is so big memory allocation difference?
function gen() {
static $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 8; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
Indexing by strings - returns 490 KB
$a = array();
for($x = 0;$x < 100000;$x++){
$a[gen()] = $x;
}
echo (memory_get_usage() / 1024) . ' KB';
Indexing by ints - returns 10790.2890625 KB (~22 times more than first case, but same ammount of information stored!)
$a = array();
for($x = 0;$x < 100000;$x++){
$a[$x] = gen();
}
echo (memory_get_usage() / 1024) . ' KB';