序列化字符串或普通PHP,解析速度更快?

时间:2010-11-14 21:34:01

标签: php performance serialization

我将要一个大小约为5 MB的文件,我有两个选项:

  1. 使用 include 功能从文件中读取普通PHP数组
  2. 使用 file_get_contents 功能从文件中读取序列化/ json转换后的数组,然后对其进行解码。
  3. 哪一个会更快?我将把它用作缓存。

2 个答案:

答案 0 :(得分:4)

最初,当我看到这个问题时,我猜到PHP +操作码缓存会比序列化的PHP更快,但经过一些基准测试我发现我错了。 unserialize的效果比require提高了约4倍。虽然通过var_export编写PHP似乎比serialize更快。 PHP格式还具有人类可读的优点。

alt text

注意:我使用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)

即使使用字节码缓存,读取序列化数组也要快得多。