首页 文章

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

提问于
浏览
1

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

  • 使用 include 函数从文件中读取 plain PHP array .

  • 使用 file_get_contents 函数从文件中读取 serialize/json converted array 然后对其进行解码 .

哪一个会更快?我将把它用作缓存 .

2 回答

  • 4

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

  • 2

    最初,当我看到这个问题时,我猜测PHP操作码缓存会比序列化的PHP更快,但经过一些基准测试我发现我错了 . unserializerequire 执行了大约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 );
    
    }
    
    ?>
    

相关问题