【问题标题】:Serialized string or plain PHP, which is faster to parse?序列化字符串还是普通 PHP,哪个解析更快?
【发布时间】:2011-05-09 22:50:24
【问题描述】:

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

  1. 使用 include 函数从文件中读取 普通 PHP 数组
  2. 使用 file_get_contents 函数从文件中读取 serialize/json 转换数组,然后对其进行解码。

哪个会更快?我打算把它用作缓存。

【问题讨论】:

  • 我认为前一个选项更快。但只有在测试和分析这两种变体后才能知道。
  • 如果数组是平面的,也要考虑 parse_ini_file
  • 你确定你没有在这里进行预优化吗?我认为这两种方法都不应该成为性能瓶颈。我会选择您更喜欢的任何一种方法,或者最适合该项目的方法。优化在这里听起来并不重要。
  • 你为什么不测试两个变种然后在这里发布结果?

标签: php performance serialization


【解决方案1】:

最初,当我查看问题时,我猜想 PHP+opcode 缓存会比序列化 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 );

}

?>

【讨论】:

  • 你是如何生成图表的? :o
  • Excel 2011 Mac,散点图。
【解决方案2】:

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

【讨论】:

  • 你这个说法的依据是什么?
  • @troelskn,这两种方法都涉及将文件加载到内存中,但选项 1 涉及完整的 php 解释器,而选项 2 仅涉及 json 解析器。 php 解释器是比 json 解析器复杂得多的机器,所以我怀疑 AndreKR 是正确的。
  • @troelskn 在我们公司,我们多次遇到这个问题,并检查了很多不同的环境,结果发现反序列化方法总是快几倍。
  • @ben_lee 也许吧。我很想知道这是猜测还是基于事实。
猜你喜欢
  • 2011-04-21
  • 2010-12-12
  • 2011-07-19
  • 2018-12-05
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
相关资源
最近更新 更多