-
-
Save mgt95/7c7a9f31c5bebedbc58e12db648a44bc to your computer and use it in GitHub Desktop.
PHP: array to object
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 | |
# Simple loop copy | |
function loop_copy($array) { | |
$object = new stdClass(); | |
foreach ($array as $key => $value) { | |
$object->$key = $value; | |
} | |
} | |
# leveraging json_decode + json_encode | |
function json_copy($array) { | |
json_decode(json_encode($array), FALSE); | |
} | |
# http://pear.php.net/package/Benchmark/ | |
# http://pear.php.net/package/Benchmark/docs/1.2.9/Benchmark/Benchmark_Timer.html | |
require 'Benchmark/Timer.php'; | |
# prepare the arrays to be copied | |
$sizes = array(5, 20, 100, 500); | |
$arrays = array(); | |
foreach ($sizes as $size) { | |
$array = array(); | |
$i = $size; | |
while ($i-- >= 0) { | |
$key = uniqid('key'); | |
$array[$key] = uniqid('value'); | |
} | |
$arrays[] = $array; | |
} | |
# Prepare timer and iterations | |
$itera = array(100, 500, 1000); | |
foreach ($itera as $i) { | |
foreach ($arrays as $array) { | |
$array_len = count($array); | |
$timer = new Benchmark_Timer(TRUE); | |
$x = $i; | |
while ($x-- >= 0) { | |
json_copy($array); | |
} | |
$timer->setMarker("json_copy with $i copies of array size $array_len"); | |
$x = $i; | |
while ($x-- >= 0) { | |
loop_copy($array); | |
} | |
$timer->setMarker("loop_copy with $i copies of array size $array_len"); | |
$timer->display(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment