Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Microbenchmark for typed property vs. setter
<?php
// Compares the performance of a trivial typehinted setter with a public typed property
define('ITERATIONS', 1_000_000);
ini_set('memory_limit', '384M');
$arrays = [];
echo "Building data...";
for ($i = 0; $i < ITERATIONS; $i++) {
$arr = [];
for ($j = 0, $max = random_int(0, 5); $j < $max; $j++) {
$arr[] = random_int(1, 10);
}
$arrays[] = $arr;
}
echo "done\n";
class WithSetter
{
protected $data;
public function set(array $data) { $this->data = $data; }
}
class WithProperty
{
public array $data;
}
$withSetter = new WithSetter();
$withProperty = new WithProperty();
$withSetterStart = microtime(true);
for ($i = 0; $i < ITERATIONS; $i++) {
$withSetter->set($arrays[$i]);
}
echo "With setter: " . (microtime(true) - $withSetterStart) . "\n";
$withPropertyStart = microtime(true);
for ($i = 0; $i < ITERATIONS; $i++) {
$withProperty->data = $arrays[$i];
}
echo "With property: " . (microtime(true) - $withPropertyStart) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment