Created
July 13, 2015 14:37
-
-
Save mente/dc739e49d16addf1fc82 to your computer and use it in GitHub Desktop.
Testing "array soft-copy" in PHP5.6
This file contains hidden or 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 | |
$byValue = function (array $value) { | |
$z = $value[2]; | |
}; | |
$byValueWrite = function (array $value) { | |
$value[] = 1; | |
array_pop($value); | |
}; | |
$byValueForeach = function (array $value) { | |
foreach ($value as $i){} | |
}; | |
$byValueForeachWrite = function (array $value) { | |
foreach ($value as $i){} | |
$value[] = 1; | |
array_pop($value); | |
}; | |
$byReference = function (array &$referenced) { | |
$z = $referenced[2]; | |
}; | |
$byReferenceWrite = function (array &$referenced) { | |
foreach ($referenced as $i) {} | |
$referenced[] = 1; | |
array_pop($referenced); | |
}; | |
$byReferenceForeach = function(array &$referenced) { | |
foreach ($referenced as $i){} | |
}; | |
$byReferenceForeachWrite = function(array &$referenced) { | |
foreach ($referenced as $i){} | |
$referenced[] = 1; | |
array_pop($referenced); | |
}; | |
function measure($closure, $id) { | |
$start = microtime(true); | |
$arr = range(1, 10000); | |
for ($i = 0; $i < 10000; $i++) { | |
$closure($arr); | |
} | |
$total = round(microtime(true) - $start, 5); | |
echo str_pad("Finished $id in", 50, '.') . "$total\n"; | |
} | |
measure($byValue, 'by value'); | |
measure($byReference, 'by reference'); | |
measure($byValueWrite, 'by value write'); | |
measure($byReferenceWrite, 'by reference write'); | |
measure($byValueForeach, 'by value foreach'); | |
measure($byReferenceForeach, 'by reference foreach'); | |
measure($byValueForeachWrite, 'by value foreach write'); | |
measure($byReferenceForeachWrite, 'by reference foreach write'); |
This file contains hidden or 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 ../test.php | |
Finished by value in..............................0.03721 | |
Finished by reference in..........................0.0364 | |
Finished by value write in........................4.97441 | |
Finished by reference write in....................4.90189 | |
Finished by value foreach in......................9.11332 | |
Finished by reference foreach in..................4.1678 | |
Finished by value foreach write in................14.68635 | |
Finished by reference foreach write in............4.3133 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment