我将要一个大小约为5 MB的文件,我有两个选项:
哪一个会更快?我将把它用作缓存。
答案 0 :(得分:4)
最初,当我看到这个问题时,我猜到PHP +操作码缓存会比序列化的PHP更快,但经过一些基准测试我发现我错了。 unserialize
的效果比require
提高了约4倍。虽然通过var_export
编写PHP似乎比serialize
更快。 PHP格式还具有人类可读的优点。
注意:我使用PHP 5.3.3运行测试并使用ram磁盘作为我的临时文件夹。
如果您有备用内存(并安装了APC),我建议您使用apc_store
。我没有对它进行基准测试,但我希望它比基于文件的缓存快得多。
<?
function writestuff( $folder, $data ) {
$start = microtime( TRUE );
file_put_contents( "$folder/array.data", serialize( $data ) );
print ( microtime( TRUE ) - $start ).",";
$start = microtime( TRUE );
file_put_contents( "$folder/array.php", "<? return ".var_export( $data, TRUE ).";" );
print ( microtime( TRUE ) - $start ).",";
}
function readstuff( $folder ) {
$start = microtime( TRUE );
$data = unserialize( file_get_contents( "$folder/array.data" ) );
print ( microtime( TRUE ) - $start ).",";
unset( $data );
apc_clear_cache();
if( ! apc_compile_file( "$folder/array.php" ) )
throw new Exception( "didn't cache" );
$start = microtime( TRUE );
$data = require( "$folder/array.php" );
print ( microtime( TRUE ) - $start )."\n";
unset( $data );
}
$folder = $_GET["folder"];
for( $i = 1; $i < 10000; $i += 10 ) {
$data = range( 0, $i );
print $i.",";
writestuff( $folder, $data );
readstuff( $folder );
}
?>
答案 1 :(得分:2)
即使使用字节码缓存,读取序列化数组也要快得多。