Skip to content

Instantly share code, notes, and snippets.

@khards
Last active July 10, 2020 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khards/3ea9358c2eaf8772ddd2bddec0e780f2 to your computer and use it in GitHub Desktop.
Save khards/3ea9358c2eaf8772ddd2bddec0e780f2 to your computer and use it in GitHub Desktop.
This gist is to show that in php objects are much fater than arrays when you need to modify the passed object/array's contents.
<?php
/**
* Test on PHP 7.2 and PHP 5.4
*
** This gist is to show that in php7.2 objects are much fater than arrays.
**
** 1: We create an object with 10 million properties
** We pass it to a function 99999 times and modify a property
** We pass it to a function by reference 99999 times and modify a parameter
**
** 2: We create an array with 10 million elements
** We pass it to a function 99 (As it's just to slow to wait) times and modify a property
** We pass it to a function by reference 99999 times and modify a parameter
**
** Results:
* 999999 x Object passing time: 0.155613
* 999999 x Object pass by reference time: 0.154327
* 99 x array passing time: 5.640978 (for just 99!)
* 999999 x array pass by reference time: 0.149588
*
* As you can see array's are ever so just marginly faster, but not enough to worry about in real life
* If you should ever pass an array and modify the contents then this is a HUGE bottleneck in your system
*
* Conclusion: Avoid modifying arrays passed to functions, or just use objects.
*/
for ($i=0;$i<=999999;$i++) {
$data['a'.$i] = $i+100000;
}
$data = (object)$data;
$time = -microtime(true);
for ($i=0;$i<=99999;$i++) {
oslow($data);
}
$time += microtime(true);
echo "Object time: \n", sprintf('%f', $time), PHP_EOL;
$time = -microtime(true);
for ($i=0;$i<=99999;$i++) {
ofast($data);
}
$time += microtime(true);
echo "Object pass by reference time: \n", sprintf('%f', $time), PHP_EOL;
function oslow($param) {
$param->a0++;
}
function ofast(&$param) {
$param->a0++;
}
/**
* Array tests
*/
unset($data);
for ($i=0;$i<=999999;$i++) {
$data['a'.$i] = $i+100000;
}
$time = -microtime(true);
for ($i=0;$i<=99;$i++) {
slow($data);
}
$time += microtime(true);
echo "array: time: \n", sprintf('%f', $time), PHP_EOL;
$time = -microtime(true);
for ($i=0;$i<=99999;$i++) {
fast($data);
}
$time += microtime(true);
echo "Array pass by reference time: \n", sprintf('%f', $time), PHP_EOL;
function slow($param) {
$param['a0']++;
}
function fast(&$param) {
$param['a0']++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment