Preferred method to store PHP arrays (json_encode vs serialize)

前端 未结 20 1899
孤独总比滥情好
孤独总比滥情好 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

    If to summ up what people say here, json_decode/encode seems faster than serialize/unserialize BUT If you do var_dump the type of the serialized object is changed. If for some reason you want to keep the type, go with serialize!

    (try for example stdClass vs array)

    serialize/unserialize:

    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 encode/decode

    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]
    

    As you can see the json_encode/decode converts all to stdClass, which is not that good, object info lost... So decide based on needs, especially if it is not only arrays...

提交回复
热议问题