一般我们把数组缓存到文件中的话,都是先要转成字符串的形式,然后再存入文本文件中,一般有两种机制把数组转成字符串, 第一种是 $str = var_export($arr, true); 第二种是 $str = serialize($arr); ? set_time_limit(50); $a = array(1,2,3); $b = array('
一般我们把数组缓存到文件中的话,都是先要转成字符串的形式,然后再存入文本文件中,一般有两种机制把数组转成字符串,
第一种是
$str = var_export($arr, true);第二种是$str = serialize($arr);set_time_limit(50);$a = array(1,2,3);$b = array('a'=>1, 'b'=>2, 'c'=>3);$c = array('a'=>array(1,2,3), 'b'=>array(4,5,6));$time1 = microtime(true);$times = 1000000; #10wfor($i=1; $i
$A = var_export($a, true);
}
$time2 = microtime(true);
for($i=1; $i
$B = var_export($b, true);
}
$time3 = microtime(true);
for($i=1; $i
$C = var_export($c, true);
}
$time4 = microtime(true);
for($i=1; $i
$X = serialize($a);
}
$time5 = microtime(true);
for($i=1; $i
$Y = serialize($b);
}
$time6 = microtime(true);
for($i=1; $i
$Z = serialize($c);
}
$time7 = microtime(true);
for($i=1; $i
$O = unserialize($X);
}
$time8 = microtime(true);
for($i=1; $i
$P = unserialize($Y);
}
$time9 = microtime(true);
for($i=1; $i
$Q = unserialize($Z);
}
$time10 = microtime(true);
$var_export_time['a'] = $time2 - $time1;
$var_export_time['b'] = $time3 - $time2;
$var_export_time['c'] = $time4 - $time3;
$serialize_time['a'] = $time5 - $time4;
$serialize_time['b'] = $time6 - $time5;
$serialize_time['c'] = $time7 - $time6;
$unserialize_time['a'] = $time8 - $time7;
$unserialize_time['b'] = $time9 - $time8;
$unserialize_time['c'] = $time10 - $time9;
print_r($var_export_time);
print_r($serialize_time);
print_r($unserialize_time);
?>
output:
Array
(
[a] => 3.3401498794556
[b] => 5.1394801139832
[c] => 8.8483898639679
)
Array
(
[a] => 1.6063709259033
[b] => 1.7033960819244
[c] => 3.4534389972687
)
Array
(
[a] => 1.6037359237671
[b] => 1.817803144455
[c] => 3.7992968559265
)
由上面数据说明:
var_export函数性能比serialize函数性能差一倍,而unserialize时间也需要和serialize差不多的时间,serialize加上unserialize时间,和用var_export时间差不多。
所以在应用的时候,如果只用于读取数据的时候,最好存成数组原型,如果只考虑写入缓存,用serialize是不错的选择,还有就是serialize还可以处理Object类型。所以应用上能广泛一些。
但如果论生成后的缓存文件大小,那还是用var_export去除数组中的换行和空白,比用serialize要小大概10%左右,这个测试我就不放上来了,有兴趣的自己可以尝试一下。原因是因为serialize函数中加入了一些冗余字符串。