Skip to content

Instantly share code, notes, and snippets.

@rayblair06
Last active May 14, 2025 18:44
Show Gist options
  • Save rayblair06/157e472b89e3007b563d55148d70f4d1 to your computer and use it in GitHub Desktop.
Save rayblair06/157e472b89e3007b563d55148d70f4d1 to your computer and use it in GitHub Desktop.
Check performance of array, SomeClass object and stdClass object against each other
<?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