Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gabrysiak/bac902401dac5ad7d5b9 to your computer and use it in GitHub Desktop.
Save gabrysiak/bac902401dac5ad7d5b9 to your computer and use it in GitHub Desktop.
<?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";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment