我需要在平面文件中存储多维数据关联数组,以便进行缓存。我可能偶尔会遇到需要将其转换为JSON以在我的web应用程序中使用,但绝大多数情况下,我将直接在PHP中使用数组。

在这个文本文件中将数组存储为JSON还是PHP序列化数组更有效?我查看了一下,似乎在最新版本的PHP(5.3)中,json_decode实际上比反序列化更快。

我目前倾向于将数组存储为JSON,因为我觉得如果有必要的话,它更容易被人阅读,它可以在PHP和JavaScript中使用,而且从我所读到的,它甚至可能更快地解码(虽然不确定编码)。

有人知道有什么陷阱吗?有人有好的基准来显示这两种方法的性能优势吗?


当前回答

首先,我修改了脚本,做了更多的基准测试(也做了1000次而不是1次):

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Make a big, honkin test array
// You may need to adjust this depth to avoid memory limit errors
$testArray = fillArray(0, 5);

$totalJsonTime = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;

for ($i = 0; $i < 1000; $i++) {
    // Time json encoding
    $start = microtime(true);
    $json = json_encode($testArray);
    $jsonTime = microtime(true) - $start;
    $totalJsonTime += $jsonTime;

    // Time serialization
    $start = microtime(true);
    $serial = serialize($testArray);
    $serializeTime = microtime(true) - $start;
    $totalSerializeTime += $serializeTime;

    if ($jsonTime < $serializeTime) {
        $totalJsonWins++;
    }
}

$totalSerializeWins = 1000 - $totalJsonWins;

// Compare them
if ($totalJsonTime < $totalSerializeTime) {
    printf("json_encode() (wins: $totalJsonWins) was roughly %01.2f%% faster than serialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
    printf("serialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_encode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}

$totalJsonTime = 0;
$totalJson2Time = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;

for ($i = 0; $i < 1000; $i++) {
    // Time json decoding
    $start = microtime(true);
    $orig = json_decode($json, true);
    $jsonTime = microtime(true) - $start;
    $totalJsonTime += $jsonTime;

    $start = microtime(true);
    $origObj = json_decode($json);
    $jsonTime2 = microtime(true) - $start;
    $totalJson2Time += $jsonTime2;

    // Time serialization
    $start = microtime(true);
    $unserial = unserialize($serial);
    $serializeTime = microtime(true) - $start;
    $totalSerializeTime += $serializeTime;

    if ($jsonTime < $serializeTime) {
        $totalJsonWins++;
    }
}

$totalSerializeWins = 1000 - $totalJsonWins;


// Compare them
if ($totalJsonTime < $totalSerializeTime) {
    printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
    printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_decode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}

// Compare them
if ($totalJson2Time < $totalSerializeTime) {
    printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJson2Time - 1) * 100);
} else {
    printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than array json_decode()\n", ($totalJson2Time / $totalSerializeTime - 1) * 100);
}

function fillArray( $depth, $max ) {
    static $seed;
    if (is_null($seed)) {
        $seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
    }
    if ($depth < $max) {
        $node = array();
        foreach ($seed as $key) {
            $node[$key] = fillArray($depth + 1, $max);
        }
        return $node;
    }
    return 'empty';
}

我使用PHP 7的这个版本:

PHP 7.0.14 (cli)(已构建:2017年1月18日19:13:23)(NTS)版权所有(c) PHP Group Zend Engine v3.0.0,版权所有(c) 1998-2016 Zend技术 与Zend OPcache v7.0.14,版权(c) 1999-2016,由Zend Technologies

我的结果是:

Serialize()(胜:999)比json_encode()快大约10.98% Unserialize()(胜:987)大约比json_decode()快33.26% Unserialize()(胜:987)大约比array快48.35% json_decode ()

显然,序列化/反序列化是最快的方法,而json_encode/decode是最可移植的方法。

如果您考虑这样一个场景:您读/写序列化数据的次数是向非php系统发送数据或从非php系统接收数据的次数的10倍或更多,那么就时间而言,最好还是使用序列化/反序列化,并在序列化之前使用json_encode或json_decode。

其他回答

我也做了一个小的基准测试。结果是一样的。但是我需要解码性能。我注意到,就像上面几个人说的,unserialize比json_decode快。反序列化大约占用json_decode时间的60-70%。所以结论很简单: 当需要编码时的性能时,使用json_encode,当需要解码时的性能时,使用unserialize。因为你不能合并这两个功能,你必须做出选择,你需要更多的性能。

我在pseudo中的基准:

用一些随机键和值定义数组$arr 对于x < 100;x + +;序列化和json_encode $arr的array_rand 对于y < 1000;y + +;Json_decode json编码的string - calc时间 对于y < 1000;y + +;取消序列化的string - calc时间 回声更快的结果

平均而言:unserialize赢得了96次胜过json_decode的4次。平均约1.5ms超过2.5ms。

似乎serialize是我要使用的一个,有两个原因:

有人指出,unserialize比json_decode更快,而且'read' case听起来比'write' case更有可能。 当使用无效UTF-8字符的字符串时,我遇到了json_encode的问题。当这种情况发生时,字符串最终为空,导致信息丢失。

您可能还会对https://github.com/phadej/igbinary感兴趣——它为PHP提供了一个不同的序列化“引擎”。

我的随机/任意的“性能”数据,使用PHP 5.3.5在64位平台上显示:

JSON:

JSON编码在2.180496931076秒 JSON解码在9.8368630409241秒 serialized "String" size: 13993

原生PHP:

PHP在2.9125759601593秒内序列化 PHP在6.4348418712616秒内反序列化 序列化的“字符串”大小:20769

Igbinary:

winigbinary在1.6099879741669秒内序列化 winigbinary在4.7737920284271秒内未序列化 WIN序列化的“字符串”大小:4467

因此,igbinary_serialize()和igbinary_unserialize()更快,使用更少的磁盘空间。

我使用fillArray(0,3)代码,但使数组键更长的字符串。

igbinary可以存储与PHP原生序列化相同的数据类型(所以对象等没有问题),如果你愿意,你可以告诉PHP5.3使用它来进行会话处理。

参见http://ilia.ws/files/zendcon_2010_hidden_features.pdf -特别是幻灯片14/15/16

如果总结一下人们在这里所说的话,json_decode/encode似乎比序列化/反序列化BUT更快 如果执行var_dump,序列化对象的类型将被更改。 如果出于某种原因想要保留类型,请使用serialize!

(例如stdClass vs array)

序列化/非系列化:

Array cache:
array (size=2)
  'a' => string '1' (length=1)
  'b' => int 2
Object cache:
object(stdClass)[8]
  public 'field1' => int 123
This cache:
object(Controller\Test)[8]
  protected 'view' => 

JSON 编码/解码

Array cache:
object(stdClass)[7]
  public 'a' => string '1' (length=1)
  public 'b' => int 2
Object cache:
object(stdClass)[8]
  public 'field1' => int 123
This cache:
object(stdClass)[8]

正如你所看到的json_encode/decode将所有转换为stdClass,这不是很好,对象信息丢失…所以根据需要来决定,特别是如果它不仅仅是数组……

我建议您使用超级缓存,这是一种不使用json_encode或序列化的文件缓存机制。与其他PHP缓存机制相比,它使用简单,速度非常快。

https://packagist.org/packages/smart-php/super-cache

Ex:

<?php
require __DIR__.'/vendor/autoload.php';
use SuperCache\SuperCache as sCache;

//Saving cache value with a key
// sCache::cache('<key>')->set('<value>');
sCache::cache('myKey')->set('Key_value');

//Retrieving cache value with a key
echo sCache::cache('myKey')->get();
?>