Skip to content

Instantly share code, notes, and snippets.

@mkorostoff
Created October 21, 2014 16:33
Show Gist options
  • Save mkorostoff/79c50cc873645a41922a to your computer and use it in GitHub Desktop.
Save mkorostoff/79c50cc873645a41922a to your computer and use it in GitHub Desktop.
<?php
//Approach 1 with json encode/decode
$obj1 = new stdClass();
$obj1->prop1 = 'hello';
$obj1->prop2 = 'world';
$obj2 = new stdClass();
$obj2->prop1 = 'hello';
$obj2->prop2 = 'world';
$arr = array($obj1, $obj2);
$time_pre = microtime(true);
for($i=0;$i<1000000;$i++){
json_decode(json_encode($arr), TRUE);
}
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
print $exec_time; //prints 5.3 seconds
//Approach 2 with type casting
$obj1 = new stdClass();
$obj1->prop1 = 'hello';
$obj1->prop2 = 'world';
$obj2 = new stdClass();
$obj2->prop1 = 'hello';
$obj2->prop2 = 'world';
$arr = array($obj1, $obj2);
$time_pre = microtime(true);
for($i=0;$i<1000000;$i++){
foreach ($arr as &$obj) {
$obj = (array) $obj;
}
}
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
print $exec_time; //prints 0.8 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment