Preferred method to store PHP arrays (json_encode vs serialize)

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

    I made a small benchmark as well. My results were the same. But I need the decode performance. Where I noticed, like a few people above said as well, unserialize is faster than json_decode. unserialize takes roughly 60-70% of the json_decode time. So the conclusion is fairly simple: When you need performance in encoding, use json_encode, when you need performance when decoding, use unserialize. Because you can not merge the two functions you have to make a choise where you need more performance.

    My benchmark in pseudo:

    • Define array $arr with a few random keys and values
    • for x < 100; x++; serialize and json_encode a array_rand of $arr
    • for y < 1000; y++; json_decode the json encoded string - calc time
    • for y < 1000; y++; unserialize the serialized string - calc time
    • echo the result which was faster

    On avarage: unserialize won 96 times over 4 times the json_decode. With an avarage of roughly 1.5ms over 2.5ms.

提交回复
热议问题