代码之家  ›  专栏  ›  技术社区  ›  KyleFarris

存储PHP数组的首选方法(json_encode vs serialize)

  •  571
  • KyleFarris  · 技术社区  · 16 年前

    我需要在一个平面文件中存储一个多维关联数据数组,用于缓存。我可能偶尔会遇到将其转换为JSON以在我的Web应用程序中使用的需求,但绝大多数时间我将直接在PHP中使用该数组。

    在这个文本文件中,将数组存储为json或php序列化数组会更有效吗?我环顾四周,在最新版本的php(5.3)中, json_decode 实际上比 unserialize .

    我目前倾向于将数组存储为json,因为我觉得它更容易被人阅读(如果需要的话),它可以在PHP和JavaScript中使用,而且从我所读到的内容来看,解码速度可能更快(但不确定编码)。

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

    19 回复  |  直到 7 年前
        1
  •  532
  •   T.Todua Laurent W.    7 年前

    取决于你的优先顺序。

    如果性能是你的绝对驾驶特性,那么一定要用最快的。在你做出选择之前,要确保你对这些差异有充分的了解。

    • 不像 serialize() 您需要添加额外的参数来保持UTF-8字符不变: json_encode($array, JSON_UNESCAPED_UNICODE) (否则,它将UTF-8字符转换为Unicode转义序列)。
    • JSON将没有对象原始类的内存(它们总是作为stdclass实例还原)。
    • 你不能利用 __sleep() __wakeup() 用JSON
    • 默认情况下,只有公共属性使用JSON序列化。中 PHP>=5.4 你可以实现 JsonSerializable 改变这种行为)。
    • JSON更便于携带

    可能还有其他一些我目前无法想到的差异。

    比较两者的简单速度测试

    <?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);
    
    // Time json encoding
    $start = microtime(true);
    json_encode($testArray);
    $jsonTime = microtime(true) - $start;
    echo "JSON encoded in $jsonTime seconds\n";
    
    // Time serialization
    $start = microtime(true);
    serialize($testArray);
    $serializeTime = microtime(true) - $start;
    echo "PHP serialized in $serializeTime seconds\n";
    
    // Compare them
    if ($jsonTime < $serializeTime) {
        printf("json_encode() was roughly %01.2f%% faster than serialize()\n", ($serializeTime / $jsonTime - 1) * 100);
    }
    else if ($serializeTime < $jsonTime ) {
        printf("serialize() was roughly %01.2f%% faster than json_encode()\n", ($jsonTime / $serializeTime - 1) * 100);
    } else {
        echo "Impossible!\n";
    }
    
    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';
    }
    
        2
  •  231
  •   Greg    16 年前

    杰森 比PHP的序列化格式更简单、更快,应该使用 除非 :

    • 您正在存储深度嵌套的数组: json_decode() :“如果JSON编码的数据超过127个元素,此函数将返回FALSE。”
    • 您正在存储需要作为正确类进行非序列化的对象
    • 您正在与不支持JSON解码的旧PHP版本进行交互
        3
  •  58
  •   Community CDub    10 年前

    我写了一篇关于这个主题的博客:“ Cache a large array: JSON, serialize or var_export? “。在本文中,我们发现对于小到大的数组,序列化是最好的选择。对于非常大的阵列(>70MB),JSON是更好的选择。

        4
  •  51
  •   David Goodwin    14 年前

    你也可能对 https://github.com/phadej/igbinary -它为PHP提供了不同的序列化“引擎”。

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

    杰森:

    • JSON在2.180496931076秒内编码
    • JSON在9.8368630409241秒内解码
    • 序列化“字符串”大小:13993

    本地PHP:

    • php在2.9125759610593秒内序列化
    • php在6.4348418712616秒内未细分
    • 序列化“字符串”大小:20769

    Igbinary:

    • igbinary在1.6099874741669秒内序列化
    • 在4.7737920284271秒内未上市
    • 序列化“字符串”大小:4467

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

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

    igbinary可以存储与php本机serialize相同的数据类型(因此对象等没有问题),如果愿意,您可以告诉php5.3使用它进行会话处理。

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

        5
  •  24
  •   Blunk    15 年前

    Y刚刚测试了serialized和json编码和解码,加上它将存储字符串的大小。

    JSON encoded in 0.067085981369 seconds. Size (1277772)
    PHP serialized in 0.12110209465 seconds. Size (1955548)
    JSON decode in 0.22470498085 seconds
    PHP serialized in 0.211947917938 seconds
    json_encode() was roughly 80.52% faster than serialize()
    unserialize() was roughly 6.02% faster than json_decode()
    JSON string was roughly 53.04% smaller than Serialized string
    

    我们可以得出这样的结论:JSON编码更快,得到的字符串更小,但非序列化对字符串解码更快。

        6
  •  15
  •   Jordan S. Jones    16 年前

    如果您正在缓存最终希望在以后某个时间点“包含”的信息,则可能需要尝试使用 var_export . 这样,您只接受“序列化”中的命中,而不接受“非序列化”中的命中。

        7
  •  11
  •   Jeff Whiting    15 年前

    我增加了测试以包括非标准化性能。这是我得到的数字。

    Serialize
    
    JSON encoded in 2.5738489627838 seconds
    PHP serialized in 5.2861361503601 seconds
    Serialize: json_encode() was roughly 105.38% faster than serialize()
    
    
    Unserialize
    
    JSON decode in 10.915472984314 seconds
    PHP unserialized in 7.6223039627075 seconds
    Unserialize: unserialize() was roughly 43.20% faster than json_decode() 
    

    因此,JSON似乎编码更快,但解码速度较慢。因此,它可能取决于您的应用程序以及您希望做的最多。

        8
  •  8
  •   urraka    15 年前

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

    • 有人指出,非序列化比JSON解码更快,“读”的情况听起来比“写”的情况更有可能。

    • 当字符串包含无效的UTF-8字符时,我遇到了JSON U编码的问题。当发生这种情况时,字符串最终为空,导致信息丢失。

        9
  •  8
  •   soyuka    11 年前

    非常好的主题,在阅读了几个答案之后,我想分享我在这个主题上的实验。

    我得到了一个用例,在这个用例中,几乎每次与数据库交谈时都需要查询一些“巨大”的表(不要问为什么,只问一个事实)。数据库缓存系统不合适,因为它不会缓存不同的请求,所以我想介绍一下PHP缓存系统。

    我试过 apcu 但是它不符合需要,在这种情况下内存不够可靠。下一步是使用序列化将数据缓存到文件中。

    表有14355个条目,有18列,这些是关于读取序列化缓存的测试和统计信息:

    杰森:

    正如你们所说,最大的不便是 json_encode / json_decode 它把一切都变成 StdClass 实例(或对象)。如果您需要循环它,那么将它转换为数组是您可能要做的,是的,它会增加转换时间。

    平均时间:780.2 ms;内存使用:41.5MB;缓存文件大小:3.8MB

    MSGPACK

    @哈奇提到 msgpack . 漂亮的网站。我们试试看,好吗?

    平均时间:497毫秒;内存使用:32MB;缓存文件大小:2.8MB

    这更好,但需要一个新的扩展;编译有时害怕的人…

    IG-二进制的

    @金格多格提到 igbinary . 注意我已经设置了 igbinary.compact_strings=Off 因为我更关心的是阅读性能而不是文件大小。

    平均时间:411.4ms;内存使用:36.75MB;缓存文件大小:3.3MB

    比味精包好。不过,这一个也需要编译。

    serialize / unserialize

    平均时间:477.2 ms;内存使用:36.25MB;缓存文件大小:5.9MB

    性能优于JSON,数组越大,速度越慢 JSONE译码 是的,但你已经是新的了。

    这些外部扩展正在缩小文件大小,在纸上看起来很好。数字不会说谎。如果得到的结果与使用标准PHP函数得到的结果几乎相同,那么编译扩展有什么意义呢?

    我们还可以推断,根据您的需要,您将选择不同于其他人的内容:

    • igbinary非常好,性能比msgpack好
    • msgpack更擅长压缩数据(请注意,我没有尝试过igbinary compact.string选项)。
    • 不想编译?使用标准。

    就是这样,另一个序列化方法比较,帮助您选择一个!

    *使用phpunit 3.7.31、php 5.5.10进行测试-仅使用标准硬盘驱动器和旧的双核CPU进行解码-在10个相同的用例测试中,平均值可能不同

        10
  •  6
  •   Mr. Sox    14 年前

    我已经在一个相当复杂、适度嵌套的多散列(其中包含各种数据(字符串、空值、整数),以及序列化/非序列化上对此进行了非常彻底的测试,结果比json_encode/json_decode快得多。

    JSON在我的测试中唯一的优势是它的“打包”尺寸更小。

    这些都是在php 5.3.3下完成的,如果您需要更多的细节,请告诉我。

    下面是测试结果,然后是生成它们的代码。我不能提供测试数据,因为它会泄露我不能在野外放手的信息。

    JSON encoded in 2.23700618744 seconds
    PHP serialized in 1.3434419632 seconds
    JSON decoded in 4.0405561924 seconds
    PHP unserialized in 1.39393305779 seconds
    
    serialized size : 14549
    json_encode size : 11520
    serialize() was roughly 66.51% faster than json_encode()
    unserialize() was roughly 189.87% faster than json_decode()
    json_encode() string was roughly 26.29% smaller than serialize()
    
    //  Time json encoding
    $start = microtime( true );
    for($i = 0; $i < 10000; $i++) {
        json_encode( $test );
    }
    $jsonTime = microtime( true ) - $start;
    echo "JSON encoded in $jsonTime seconds<br>";
    
    //  Time serialization
    $start = microtime( true );
    for($i = 0; $i < 10000; $i++) {
        serialize( $test );
    }
    $serializeTime = microtime( true ) - $start;
    echo "PHP serialized in $serializeTime seconds<br>";
    
    //  Time json decoding
    $test2 = json_encode( $test );
    $start = microtime( true );
    for($i = 0; $i < 10000; $i++) {
        json_decode( $test2 );
    }
    $jsonDecodeTime = microtime( true ) - $start;
    echo "JSON decoded in $jsonDecodeTime seconds<br>";
    
    //  Time deserialization
    $test2 = serialize( $test );
    $start = microtime( true );
    for($i = 0; $i < 10000; $i++) {
        unserialize( $test2 );
    }
    $unserializeTime = microtime( true ) - $start;
    echo "PHP unserialized in $unserializeTime seconds<br>";
    
    $jsonSize = strlen(json_encode( $test ));
    $phpSize = strlen(serialize( $test ));
    
    echo "<p>serialized size : " . strlen(serialize( $test )) . "<br>";
    echo "json_encode size : " . strlen(json_encode( $test )) . "<br></p>";
    
    //  Compare them
    if ( $jsonTime < $serializeTime )
    {
        echo "json_encode() was roughly " . number_format( ($serializeTime / $jsonTime - 1 ) * 100, 2 ) . "% faster than serialize()";
    }
    else if ( $serializeTime < $jsonTime )
    {
        echo "serialize() was roughly " . number_format( ($jsonTime / $serializeTime - 1 ) * 100, 2 ) . "% faster than json_encode()";
    } else {
        echo 'Unpossible!';
    }
        echo '<BR>';
    
    //  Compare them
    if ( $jsonDecodeTime < $unserializeTime )
    {
        echo "json_decode() was roughly " . number_format( ($unserializeTime / $jsonDecodeTime - 1 ) * 100, 2 ) . "% faster than unserialize()";
    }
    else if ( $unserializeTime < $jsonDecodeTime )
    {
        echo "unserialize() was roughly " . number_format( ($jsonDecodeTime / $unserializeTime - 1 ) * 100, 2 ) . "% faster than json_decode()";
    } else {
        echo 'Unpossible!';
    }
        echo '<BR>';
    //  Compare them
    if ( $jsonSize < $phpSize )
    {
        echo "json_encode() string was roughly " . number_format( ($phpSize / $jsonSize - 1 ) * 100, 2 ) . "% smaller than serialize()";
    }
    else if ( $phpSize < $jsonSize )
    {
        echo "serialize() string was roughly " . number_format( ($jsonSize / $phpSize - 1 ) * 100, 2 ) . "% smaller than json_encode()";
    } else {
        echo 'Unpossible!';
    }
    
        11
  •  5
  •   Jelmer    12 年前

    我也做了一个小基准。我的结果是一样的。但我需要解码性能。我注意到,就像上面提到的一些人一样, unserialize 比快 json_decode . 序列化 大约占 JSONE译码 时间。所以结论相当简单: 当需要编码性能时,请使用 json_encode ,解码时需要性能时,请使用 序列化 . 因为不能合并这两个函数,所以必须在需要更高性能的地方进行选择。

    我的伪基准:

    • 用几个随机键和值定义数组$arr
    • 对于x<100;x++;序列化和json_编码$arr的数组_rand
    • 对于y<1000;y++;json_,解码json编码的字符串-计算时间
    • 对于Y<1000;Y++;取消序列化字符串的序列化-计算时间
    • 回响更快的结果

    在avarage:unserialize赢得96次超过4倍的JSON解码。在2.5毫秒以上的时间内,可用率约为1.5毫秒。

        12
  •  2
  •   too much php    15 年前

    在做出最终决定之前,请注意JSON格式对于关联数组是不安全的。- json_decode() 将它们作为对象返回:

    $config = array(
        'Frodo'   => 'hobbit',
        'Gimli'   => 'dwarf',
        'Gandalf' => 'wizard',
        );
    print_r($config);
    print_r(json_decode(json_encode($config)));
    

    输出为:

    Array
    (
        [Frodo] => hobbit
        [Gimli] => dwarf
        [Gandalf] => wizard
    )
    stdClass Object
    (
        [Frodo] => hobbit
        [Gimli] => dwarf
        [Gandalf] => wizard
    )
    
        13
  •  1
  •   Hutch    12 年前

    仅供参考——如果您希望将数据序列化为易于阅读和理解的内容(如JSON),但具有更多的压缩和更高的性能,则应该签出 messagepack.

        14
  •  1
  •   Pink Code    10 年前

    在这里查看结果(很抱歉黑客将PHP代码放在JS代码框中):

    http://jsfiddle.net/newms87/h3b0a0ha/embedded/result/

    结果: serialize() unserialize() 在不同大小的数组上,php 5.4都快得多。

    我在现实数据上做了一个测试脚本,用于比较JSON编码与序列化,以及JSON解码与非序列化。测试是在一个生产中的电子商务站点的缓存系统上运行的。它只需获取缓存中已经存在的数据,并测试对所有数据进行编码/解码(或序列化/非序列化)的时间,然后将其放入一个易于查看的表中。

    我在php 5.4共享主机服务器上运行了这个。

    结果是非常确凿的,对于这些大到小的数据集,序列化和非序列化是明显的赢家。特别是在我的用例中,JSON解码和非序列化对于缓存系统来说是最重要的。在这里,非宗教化几乎是无处不在的赢家。它通常是JSON解码的2到4倍(有时是6到7倍)。

    注意到@peter bailey结果的差异是很有趣的。

    下面是用于生成结果的PHP代码:

    <?php
    
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
    
    function _count_depth($array)
    {
        $count     = 0;
        $max_depth = 0;
        foreach ($array as $a) {
            if (is_array($a)) {
                list($cnt, $depth) = _count_depth($a);
                $count += $cnt;
                $max_depth = max($max_depth, $depth);
            } else {
                $count++;
            }
        }
    
        return array(
            $count,
            $max_depth + 1,
        );
    }
    
    function run_test($file)
    {
        $memory     = memory_get_usage();
        $test_array = unserialize(file_get_contents($file));
        $memory     = round((memory_get_usage() - $memory) / 1024, 2);
    
        if (empty($test_array) || !is_array($test_array)) {
            return;
        }
    
        list($count, $depth) = _count_depth($test_array);
    
        //JSON encode test
        $start            = microtime(true);
        $json_encoded     = json_encode($test_array);
        $json_encode_time = microtime(true) - $start;
    
        //JSON decode test
        $start = microtime(true);
        json_decode($json_encoded);
        $json_decode_time = microtime(true) - $start;
    
        //serialize test
        $start          = microtime(true);
        $serialized     = serialize($test_array);
        $serialize_time = microtime(true) - $start;
    
        //unserialize test
        $start = microtime(true);
        unserialize($serialized);
        $unserialize_time = microtime(true) - $start;
    
        return array(
            'Name'                   => basename($file),
            'json_encode() Time (s)' => $json_encode_time,
            'json_decode() Time (s)' => $json_decode_time,
            'serialize() Time (s)'   => $serialize_time,
            'unserialize() Time (s)' => $unserialize_time,
            'Elements'               => $count,
            'Memory (KB)'            => $memory,
            'Max Depth'              => $depth,
            'json_encode() Win'      => ($json_encode_time > 0 && $json_encode_time < $serialize_time) ? number_format(($serialize_time / $json_encode_time - 1) * 100, 2) : '',
            'serialize() Win'        => ($serialize_time > 0 && $serialize_time < $json_encode_time) ? number_format(($json_encode_time / $serialize_time - 1) * 100, 2) : '',
            'json_decode() Win'      => ($json_decode_time > 0 && $json_decode_time < $serialize_time) ? number_format(($serialize_time / $json_decode_time - 1) * 100, 2) : '',
            'unserialize() Win'      => ($unserialize_time > 0 && $unserialize_time < $json_decode_time) ? number_format(($json_decode_time / $unserialize_time - 1) * 100, 2) : '',
        );
    }
    
    $files = glob(dirname(__FILE__) . '/system/cache/*');
    
    $data = array();
    
    foreach ($files as $file) {
        if (is_file($file)) {
            $result = run_test($file);
    
            if ($result) {
                $data[] = $result;
            }
        }
    }
    
    uasort($data, function ($a, $b) {
        return $a['Memory (KB)'] < $b['Memory (KB)'];
    });
    
    $fields = array_keys($data[0]);
    ?>
    
    <table>
        <thead>
        <tr>
            <?php foreach ($fields as $f) { ?>
                <td style="text-align: center; border:1px solid black;padding: 4px 8px;font-weight:bold;font-size:1.1em"><?= $f; ?></td>
            <?php } ?>
        </tr>
        </thead>
    
        <tbody>
        <?php foreach ($data as $d) { ?>
            <tr>
                <?php foreach ($d as $key => $value) { ?>
                    <?php $is_win = strpos($key, 'Win'); ?>
                    <?php $color = ($is_win && $value) ? 'color: green;font-weight:bold;' : ''; ?>
                    <td style="text-align: center; vertical-align: middle; padding: 3px 6px; border: 1px solid gray; <?= $color; ?>"><?= $value . (($is_win && $value) ? '%' : ''); ?></td>
                <?php } ?>
            </tr>
        <?php } ?>
        </tbody>
    </table>
    
        15
  •  1
  •   Divyang Desai Jonny B'Good    8 年前

    首先,我更改了脚本以进行更多的基准测试(还执行了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) 1997-2016 PHP Group Zend Engine v3.0.0,版权所有(c)1998-2016 Zend技术 Zend Opcache V7.0.14,版权所有(C)1999-2016,Zend Technologies

    我的结果是:

    serialize()(wins:999)比json_encode()快10.98%。 unserialize()(wins:987)比json-decode()快33.26%。 unserialize()(wins:987)比array快大约48.35%。 JSON-DECODE()

    所以 清晰地 ,序列化/非序列化是 最快的 方法,而json_编码/解码是 最便携。

    如果您考虑一个场景,您读/写序列化数据的频率是10倍,或者比从非PHP系统发送或接收的频率更高,那么您最好使用序列化/非序列化,并在序列化之前让它json_编码或json_解码。

        16
  •  0
  •   Informate.it    13 年前

    如果您想备份数据并将其恢复到另一台机器上或通过ftp,JSON更好。

    例如,对于serialize,如果您将数据存储在Windows服务器上,请通过ftp下载数据并将其还原到Linux服务器上,由于charachter重新编码,它将无法再工作,因为serialize存储字符串的长度,并且以unicode>utf-8转码,某些1字节的characher可能变为2字节长,从而导致算法崩溃。

        17
  •  0
  •   gmadd Charles    13 年前

    THX-对于此基准代码:

    我在用于配置的数组上的结果如下: json编码0.003151783599854秒
    php在0.003796100664551秒内序列化
    json_encode() serialize() json编码0.0070841312408447秒
    php在0.0035839080810547秒内序列化
    unserialize() JSON-EnCODE()

    所以-用你自己的数据测试它。

        18
  •  0
  •   David Constantine    7 年前

    如果要总结人们在这里所说的话,json解码/编码似乎比序列化/非序列化快,但是 如果执行var_dump,则会更改序列化对象的类型。 如果出于某种原因要保留该类型,请使用序列化!

    (例如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_编码/解码将所有转换为stdclass,这不是很好,对象信息丢失…所以要根据需要来决定,特别是如果它不仅仅是数组…

        19
  •  0
  •   shabeer    7 年前

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

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

    前任:

    <?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();
    ?>