使用mc时,我们会考虑数据的存储格式;php的函数允许我们直接set一个数组到mc里,取出来后也可以直接当做数组来用,确实很简单,但是和json格式比较了一下才发现,简单的代价是浪费了更大的空间,下面是一个小的测试程序:
<?php
$host = "10.10.10.10";
$port = "11211";
$uid = "103630";
$p1 = array(
"et"=>"103630", // expire time
"pt"=>"103630", //
"pv"=>"103630",
"ut"=>"103630",
"st"=>"103630",
"pp"=>"103630",
"s"=>"103630",
"ot"=>"103630"
);
$data[] = $p1;
$mc = new Memcache();
$mc->connect($host,$port);
$mc->set(103631,$data);
$mc->set(103632,json_encode($data));
?>
telnet 10.10.10.10 11211
get 103631
VALUE 103631 1 191
a:1:{i:0;a:8:{s:2:"et";s:6:"103630";s:2:"pt";s:6:"103630";s:2:"pv";s:6:"103630";s:2:"ut";s:6:"103630";s:2:"st";s:6:"103630";s:2:"pp";s:6:"103630";s:1:"s";s:6:"103630";s:2:"ot";s:6:"103630";}}
END
get 103632
VALUE 103632 0 114
[{"et":"103630","pt":"103630","pv":"103630","ut":"103630","st":"103630","pp":"103630","s":"103630","ot":"103630"}]
END
可见json还是比较节省内存空间的。
但是php可以序列化除了resource类型之外的所有类型。而json只能序列化四种,而且表达非常简洁