simdjson_php(github.com/crazyxman/s…)是一个php扩展,它绑定simdjson来实现快速解析,simdjson是一个高速的json解析器,它使用了大多数SIMD单一指令。simdjson介绍:github.com/lemire/simd…php
//检查字符串是否为一个有效的json:
$isValid = simdjson_isvalid($jsonString); //return bool
//解析一个json字符串,返回数组,对象,null,相似json_decode(),第三个参数为解析的深度
$parsedJSON = simdjson_decode($jsonString, true, 512); //return array|object|null. "null" string is not a standard json
/* { "Image": { "Width": 800, "Height": 600, "Title": "View from 15th Floor", "Thumbnail": { "Url": "http://www.example.com/image/481989943", "Height": 125, "Width": 100 }, "Animated" : false, "IDs": [116, 943, 234, 38793, {"p": "30"}] } } */
//注意. "\t" 是一个分割符. 它必须是一个控制字符. 它用来分割对象的key或数组的下标
//例如. "Image\tThumbnail\tUrl" 是正确. 'Image\tThumbnail\tUrl' 是错误的
//根据json串获取指定key的值
$value = simdjson_key_value($jsonString, "Image\tThumbnail\tUrl");
var_dump($value); // string(38) "http://www.example.com/image/481989943"
$value = simdjson_key_value($jsonString, "Image\tIDs\t4", true);
var_dump($value);
/* array(1) { ["p"]=> string(2) "30" } */
//获取json解析后的资源,只解析一次,后续使用再也不解析
$resource = simdjson_resource($jsonString);
//根据json资源获取指定key的值
$value = simdjson_key_value($resource, "Image\tThumbnail\tUrl");
var_dump($value); // string(38) "http://www.example.com/image/481989943"
$value = simdjson_key_value($resource, "Image\tIDs\t4", true);
var_dump($value);
/* array(1) { ["p"]=> string(2) "30" } */
//检查key是否存在,参数能够是一个json串也能够是一个json资源,返回true,false,null。当第一个参数是字符串时返回null表明解析失败
$res = simdjson_key_exists($jsonString, "Image\tIDs\t1");
var_dump($res) //bool(true)
$res = simdjson_key_exists($resource, "Image\tIDs\t1");
var_dump($res) //bool(true)
复制代码
filename | json_decode | simdjson_decode | simdjson_isvalid |
---|---|---|---|
apache_builds.json | 0.00307300 | 0.00225200 | 0.00018100 |
canada.json | 0.13955000 | 0.02773900 | 0.00358300 |
citm_catalog.json | 0.03030900 | 0.01334000 | 0.00117000 |
github_events.json | 0.00294100 | 0.00090400 | 0.00008500 |
gsoc-2018.json | 0.04292500 | 0.01112000 | 0.00186700 |
instruments.json | 0.00509700 | 0.00231800 | 0.00017500 |
marine_ik.json | 0.09833600 | 0.04417500 | 0.00463400 |
mesh.json | 0.01869200 | 0.00722600 | 0.00114800 |
mesh.pretty.json | 0.03576200 | 0.00738100 | 0.00163400 |
numbers.json | 0.00263600 | 0.00069900 | 0.00018200 |
random.json | 0.01713500 | 0.00973900 | 0.00063000 |
twitter.json | 0.01258600 | 0.00618400 | 0.00057400 |
twitterescaped.json | 0.01435900 | 0.00650400 | 0.00074300 |
update-center.json | 0.01506000 | 0.00869100 | 0.00047800 |
You may run the benchmarks by running the commands:git
若有不足之处下方留言便可,欢迎你们批评指正,我会虚心接纳。github