Last active
May 14, 2025 18:44
-
-
Save rayblair06/157e472b89e3007b563d55148d70f4d1 to your computer and use it in GitHub Desktop.
Check performance of array, SomeClass object and stdClass object against each other
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 | |
| class SomeClass { | |
| public $aaa; | |
| public $bbb; | |
| public $ccc; | |
| } | |
| function p($data) { | |
| echo '<pre>'; | |
| print_r($data); | |
| echo '</pre>'; | |
| } | |
| function benchmark_array() { | |
| $startTime = microtime(true); | |
| $arrays = []; | |
| $startMemory = memory_get_usage(); | |
| for ($i = 0; $i < 1000; $i++) { | |
| $item = []; | |
| for ($j = 0; $j < 1000; $j++) { | |
| $item['aaa'] = 'aaa'; | |
| $item['bbb'] = 'bbb'; | |
| $item['ccc'] = $item['aaa'] . $item['bbb']; | |
| } | |
| $arrays[] = $item; | |
| } | |
| $endMemory = memory_get_usage(); | |
| echo '<p>Array time: ' . (microtime(true) - $startTime) . '</p>'; | |
| echo '<p>Memory used: ' . ($endMemory - $startMemory) . '</p>'; | |
| p($item); | |
| } | |
| function benchmark_someclass() { | |
| $startTime = microtime(true); | |
| $arrays = []; | |
| $startMemory = memory_get_usage(); | |
| for ($i = 0; $i < 1000; $i++) { | |
| $item = new SomeClass(); | |
| for ($j = 0; $j < 1000; $j++) { | |
| $item->aaa = 'aaa'; | |
| $item->bbb = 'bbb'; | |
| $item->ccc = $item->aaa . $item->bbb; | |
| } | |
| $arrays[] = $item; | |
| } | |
| $endMemory = memory_get_usage(); | |
| echo '<p>SomeClass time: ' . (microtime(true) - $startTime) . '</p>'; | |
| echo '<p>Memory used: ' . ($endMemory - $startMemory) . '</p>'; | |
| p($item); | |
| } | |
| function benchmark_stdclass() { | |
| $startTime = microtime(true); | |
| $arrays = []; | |
| $startMemory = memory_get_usage(); | |
| for ($i = 0; $i < 1000; $i++) { | |
| $item = new stdClass(); | |
| for ($j = 0; $j < 1000; $j++) { | |
| $item->aaa = 'aaa'; | |
| $item->bbb = 'bbb'; | |
| $item->ccc = $item->aaa . $item->bbb; | |
| } | |
| $arrays[] = $item; | |
| } | |
| $endMemory = memory_get_usage(); | |
| echo '<p>stdClass time: ' . (microtime(true) - $startTime) . '</p>'; | |
| echo '<p>Memory used: ' . ($endMemory - $startMemory) . '</p>'; | |
| p($item); | |
| } | |
| // Run benchmarks | |
| benchmark_array(); | |
| benchmark_someclass(); | |
| benchmark_stdclass(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment