许多程序员喜欢使用true作为
json_decode的第二个参数,因为返回的assoc数组将非常类似于在javascript中处理对象的方式。
返回一个正确的对象将需要阅读关于如何使用和没有,并且由于大多数程序员非常熟悉关联数组,这是更可取的,特别是如果代码将由一组开发人员维护。代码应该很容易理解。
关于表现的问题,我不认为你需要担心,因为大多数(全部)案例中的瓶颈将在其他地方。除非你正在解析一个巨大的字符串,而且我的意思是真的很大,你不应该需要做任何基准。我相信返回一个assoc数组和一个正确的对象之间的区别将是很小的。
性能基准(解析)
我发现一个相当大的json字符串here并进行了一些调整,使其更大,最终大小是84 578字节。
然后我使用两种替代方案(关联数组对对象)解析字符串,每次1000次,我运行了三次测试。结果如下:
第一次跑
JSON object exec: 4.06122 s
JSON assoc exec: 3.28679 s
-------------------------------------
assoc is faster by 19.07%
第二次跑
JSON object exec: 4.09614 s
JSON assoc exec: 3.29216 s
-------------------------------------
assoc is faster by 19.63%
第三次跑
JSON object exec: 4.08762 s
JSON assoc exec: 3.29960 s
-------------------------------------
assoc is faster by 19.28%
性能基准(读/写)
这个基准是为了显示stdObject和Array()中哪一个更快,我使用一个被解析的修改后的json文件(较大的)比上一个基准。
每次读/写测试运行10万次(即,下面给出的代码执行了很多次)。
json_decode($ json_data)
for ($i =0; $i < 24; ++$i){
$a = $object[$i]->user->profile_sidebar_border_color . "stackoverflow";
$object[$i]->nested->entities->user_mentions[0]->indices[$i&1] += 1;
}
json_decode($ json_data,true)
for ($i =0; $i < 24; ++$i){
$a = $assoc[$i]['user']['profile_sidebar_border_color'] . "stackoverflow";
$assoc[$i]['nested']['entities']['user_mentions'][0]['indices'][$i&1] += 1;
}
第一次跑
JSON object read/write: 3.05421 s
JSON assoc read/write: 2.51932 s
-------------------------------------
assoc is faster by 17.51%
第二次跑
JSON object read/write: 3.06307 s
JSON assoc read/write: 2.52701 s
-------------------------------------
assoc is faster by 17.50%
第三次跑
JSON object read/write: 3.06109 s
JSON assoc read/write: 2.52248 s
-------------------------------------
assoc is faster by 17.60%
PHP版本
PHP 5.3.6 (cli) (built: Aug 13 2011 19:04:57) Copyright (c) 1997-2011
The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend
Technologies