Preferred method to store PHP arrays (json_encode vs serialize)

前端 未结 20 1926
孤独总比滥情好
孤独总比滥情好 2020-11-22 05:55

I need to store a multi-dimensional associative array of data in a flat file for caching purposes. I might occasionally come across the need to convert it to JSON for use in

20条回答
  •  一生所求
    2020-11-22 06:32

    Depends on your priorities.

    If performance is your absolute driving characteristic, then by all means use the fastest one. Just make sure you have a full understanding of the differences before you make a choice

    • Unlike serialize() you need to add extra parameter to keep UTF-8 characters untouched: json_encode($array, JSON_UNESCAPED_UNICODE) (otherwise it converts UTF-8 characters to Unicode escape sequences).
    • JSON will have no memory of what the object's original class was (they are always restored as instances of stdClass).
    • You can't leverage __sleep() and __wakeup() with JSON
    • By default, only public properties are serialized with JSON. (in PHP>=5.4 you can implement JsonSerializable to change this behavior).
    • JSON is more portable

    And there's probably a few other differences I can't think of at the moment.

    A simple speed test to compare the two

提交回复
热议问题