首页 > json or serialize

json or serialize

Preferred method to store PHP arrays (json_encode vs serialize)
大都推荐json_encode,大家实际中用哪个?


<?php
    $arr   = array("one", "two", "three", "four", "four", "four", "four");
    $start = microtime(true);
    for($i = 1; $i<1000000; $i++){
        $string = json_encode($arr);
    }
    $end   = microtime(true);
    echo $end - $start;
    
    echo "<hr>";
    
    $arr   = array("one", "two", "three", "four", "four", "four", "four");
    $start = microtime(true);
    for($i = 1; $i<1000000; $i++){
        $string = serialize($arr);
    }
    $end   = microtime(true);
    echo $end - $start;

分析了一下时间,json_encode 比serialize 更胜一筹。如果从跨语言角度+数据库说。存JSON的话,其他语言如果有访问数据库的需要,那么json_encode 就是必备了。


通常无论是json_encode还是serialize都不会成为性能瓶颈,所以抛开性能,而考虑可读性、可扩展而言,json_encode最终的胜出:

json_encode serialize
可读性 基本不可读
可扩展 高,其他语言都能解析 只能PHP自己玩
【热门文章】
【热门文章】