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