PHP中json_encode、json_decode与serialize、unserialize

json_encode和json_decode的效率并没有比serialize和unserialize的效率高,在反序列化的时候性能相差两倍左右,PHP 5.3执行效率比PHP 5.2略有提升,代码如下:

  1. <?php
  2. $target = array (
  3. 'name' => '全能头盔',
  4. 'quality' => 'Blue',
  5. 'ti_id' => 21302,
  6. 'is_bind' => 1,
  7. 'demand_conditions' =>
  8. array (
  9. 'HeroLevel' => 1,
  10. ),
  11. 'quality_attr_sign' =>
  12. array (
  13. 'HeroStrength' => 8,
  14. 'HeroAgility' => 8,
  15. 'HeroIntelligence' => 8,
  16. ),
  17. );
  18. $json = json_encode($target);
  19. $seri = serialize($target);
  20. echo "json : " . strlen($json) . " ";
  21. echo "serialize : " . strlen($seri) . " ";
  22. $stime = microtime(true);
  23. for ($i = 0; $i < 10000; $i ++)
  24. {
  25. json_encode($target);
  26. }
  27. $etime = microtime(true);
  28. echo "json_encode : " . ($etime - $stime) . " ";
  29. //----------------------------------
  30. $stime = microtime(true);
  31. for ($i = 0; $i < 10000; $i ++)
  32. {
  33. json_decode($json);
  34. }
  35. $etime = microtime(true);
  36. echo "json_decode : " . ($etime - $stime) . " ";
  37. //----------------------------------
  38. $stime = microtime(true);
  39. for ($i = 0; $i < 10000; $i ++)
  40. {
  41. serialize($target);
  42. }
  43. $etime = microtime(true);
  44. echo "serialize : " . ($etime - $stime) . " ";
  45. //----------------------------------
  46. $stime = microtime(true);
  47. for ($i = 0; $i < 10000; $i ++)
  48. {
  49. unserialize($seri); //开源代码phpfensi.com
  50. }
  51. $etime = microtime(true);
  52. echo "unserialize : " . ($etime - $stime) . " ";
  53. echo 'DONE.';
  54. ?>