by no_gravity · 7y ago · 0 comments
Because the JSON grammar is much simpler than
JavaScript’s grammar, JSON can be parsed more
efficiently than JavaScript.
Hmm.. shouldn't that hold for most programming languages then?Let's try it for PHP:
time php -r 'for ($i=0;$i<10000000; $i++) $data = [1,2,3];'
real 0m0,173s
user 0m0,161s
sys 0m0,012s
time php -r 'for ($i=0;$i<10000000; $i++) $data = json_decode("[1,2,3]");'
real 0m4,125s
user 0m4,120s
sys 0m0,005s
So for 10 million repetitions, a small PHP structure is about 20x faster then parsing JSON. But to test the point of the article, one should use the sama data structure it uses (https://raw.githubusercontent.com/WebKit/webkit/ffdd2799d323...) and parse it only once. time for f in `seq 1000` ; do php -r '$data=[1,2,3];'; done
real 0m11.169s
user 0m6.765s
sys 0m4.477s time for f in `seq 1000` ; do php -r '$data=json_decode("[1,2,3]");'; done
real 0m9.997s
user 0m6.093s
sys 0m3.974sThe correct comparison would be to try it on the 7MB json data the article is based on.
JS object literals allow such fun things as:
{
"foo": "bar",
foo1: function () { return "bar" },
foo2: () => "bar",
foo3 () { return "bar" },
get foo4 () { return "bar" },
["foo5"]: () => "bar"
}> Because the JSON grammar is much simpler than JavaScript’s grammar, JSON can be parsed more efficiently than JavaScript.
PHP does not re-parse code during execution.
$ time php -r 'for ($i=0;$i<10000000; $i++) $data = eval("[1,2,3];");'
real 0m10.568s
user 0m10.539s
sys 0m0.028sThe differences in data structures between the two languages may also play a significant role, what with PHP using complex z-val structs behind the scenes for almost all data types.