Created
February 10, 2010 14:38
-
-
Save ysbaddaden/300366 to your computer and use it in GitHub Desktop.
PHP's serialize() is slower than json_encode()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Results: | |
json_encode: 14.230s | 392 Ko | |
serialize: 50.383s | 540 Ko | |
json_decode: 36.503s | |
unserialize: 40.666s |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
date_default_timezone_set('Europe/Paris'); | |
$dates = dates_for_period('-10 years', '+10 years'); | |
$data = array(); | |
foreach($dates as $date) | |
{ | |
$year = substr($date, 0, 4); | |
$month = substr($date, 4, 2); | |
$day = substr($date, 6, 2); | |
foreach(array('18-25', '26-35', '36-45', '46-55', '56-65', '66+') as $age) { | |
$data[$age][$year][$month][$day] = rand(10, 1000); | |
} | |
} | |
benchmark('json_encode', array($data), 1000); | |
benchmark('serialize', array($data), 1000); | |
benchmark('json_decode', array(json_encode($data), true), 1000); | |
benchmark('unserialize', array(serialize($data)), 1000); | |
function benchmark($func, $args, $times) | |
{ | |
$time = microtime(true); | |
for ($i=0; $i<1000; $i++) { | |
call_user_func_array($func, $args); | |
} | |
$time = microtime(true) - $time; | |
$str = call_user_func_array($func, $args); | |
if (is_string($str)) | |
{ | |
$size = strlen($str); | |
printf("$func: %.3fs | %d Ko\n", $time, $size / 1024); | |
} | |
else { | |
printf("$func: %.3fs\n", $time); | |
} | |
} | |
function & dates_for_period($from, $to) | |
{ | |
$dates = array(); | |
$from = strtotime($from); | |
$to = strtotime($to); | |
$i = 0; | |
do | |
{ | |
$time = strtotime("-{$i} day", $to); | |
if ($time < $from) { | |
break; | |
} | |
$dates[] = date('Ymd', $time); | |
$i++; | |
} | |
while(true); | |
sort($dates); | |
return $dates; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment