Create a gist now

Instantly share code, notes, and snippets.

<?php
header("Content-Type: text/plain");
$dataIn = (object)array(
"string" => "value 1",
"array" => array(1,2,3),
"assoc" => array("cow"=>"moo","dog"=>"woof"),
"object" => (object)array("cat"=>"miao","pig"=>"oink"),
);
print "------ Data IN\n";
var_dump($dataIn);
print "\n------ JSON Representation\n";
$json = json_serialize($dataIn);
print $json;
print "\n\n------ Data OUT\n";
$dataOut = json_unserialize($json);
var_dump($dataOut);
function json_serialize($any) {
return json_encode(json_wrap($any));
}
function json_unserialize($str) {
return json_unwrap(json_decode($str));
}
function json_wrap($any, $skipAssoc = false) {
if (!$skipAssoc && is_array($any) && is_string(key($any))) {
return (object)array("_PHP_ASSOC" => json_wrap($any,true));
}
if (is_array($any) || is_object($any)) {
foreach ($any as &$v) {
$v = json_wrap($v);
}
}
return $any;
}
function json_unwrap($any, $skipAssoc = false) {
if (!$skipAssoc && is_object($any) && is_object($any->_PHP_ASSOC) && count((array)$any) == 1) {
return (array)json_unwrap($any->_PHP_ASSOC);
}
if (is_array($any) || is_object($any)) {
foreach ($any as &$v) {
$v = json_unwrap($v);
}
}
return $any;
}
print "\n\n------ Benchmarks\n";
gauge("json_serialize", 1000, function() use ($dataIn) {
json_serialize($dataIn);
});
gauge("json_unserialize", 1000, function() use ($json) {
json_unserialize($json);
});
gauge("json_encode", 1000, function() use ($dataIn) {
json_encode($dataIn);
});
gauge("json_decode", 1000, function() use ($json) {
json_decode($json);
});
function gauge($label, $times, $callback) {
$tstart = microtime(true);
for ($i=0; $i<$times; $i++) {
$callback();
}
$tend = microtime(true);
$took = ($tend-$tstart);
print (ceil($took*1000)/1000)." to run $label run $times times\n";
}
?>
------ Data IN
object(stdClass)#2 (4) {
["string"]=>
string(7) "value 1"
["array"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
["assoc"]=>
array(2) {
["cow"]=>
string(3) "moo"
["dog"]=>
string(4) "woof"
}
["object"]=>
object(stdClass)#1 (2) {
["cat"]=>
string(4) "miao"
["pig"]=>
string(4) "oink"
}
}
------ JSON Representation
{"string":"value 1","array":[1,2,3],"assoc":{"_PHP_ASSOC":{"cow":"moo","dog":"woof"}},"object":{"cat":"miao","pig":"oink"}}
------ Data OUT
object(stdClass)#4 (4) {
["string"]=>
string(7) "value 1"
["array"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
["assoc"]=>
array(2) {
["cow"]=>
string(3) "moo"
["dog"]=>
string(4) "woof"
}
["object"]=>
object(stdClass)#7 (2) {
["cat"]=>
string(4) "miao"
["pig"]=>
string(4) "oink"
}
}
------ Benchmarks
1.057 to run json_serialize run 1000 times
0.038 to run json_unserialize run 1000 times
0.324 to run json_encode run 1000 times
0.009 to run json_decode run 1000 times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment