Skip to content

Instantly share code, notes, and snippets.

@iansltx
Created April 10, 2020 21:19
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 iansltx/0ba7e1bab99f78f0dd56453721f36eb3 to your computer and use it in GitHub Desktop.
Save iansltx/0ba7e1bab99f78f0dd56453721f36eb3 to your computer and use it in GitHub Desktop.
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