-
-
Save pronskiy/492a0590d0fd3cfa0a02a2d7f908c494 to your computer and use it in GitHub Desktop.
Benchmarks of accessing properties
This file contains 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 | |
class Test { | |
// Enforce type using typed property. | |
public string $publicTypedProp = "default"; | |
// Enforce type by going through getter and setter. | |
private $privateProp = "default"; | |
public function getPrivateProp(): string { | |
return $this->privateProp; | |
} | |
public function setPrivateProp(string $value): void { | |
$this->privateProp = $value; | |
} | |
public function setPrivatePropNoType($value) { | |
$this->privateProp = $value; | |
} | |
// Enforce type by going through getter and setter, | |
// but make it look like a normal property access using magic. | |
public function __get(string $name) { | |
return $this->{'get'.$name}(); | |
} | |
public function __set(string $name, $value): void { | |
$this->{'set'.$name}($value); | |
} | |
} | |
$n = 100000000; | |
$obj = new Test; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$obj->publicTypedProp = "new"; | |
} | |
echo "Set typed public property: ", microtime(true) - $startTime, "s\n"; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$obj->setPrivatePropNoType("new"); | |
} | |
echo "Set via setter (no type check): ", microtime(true) - $startTime, "s\n"; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$obj->setPrivateProp("new"); | |
} | |
echo "Set private property via setter: ", microtime(true) - $startTime, "s\n"; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$obj->privateProp = "new"; | |
} | |
echo "Set private property via magic: ", microtime(true) - $startTime, "s\n"; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$value = $obj->publicTypedProp; | |
} | |
echo "Get typed public property: ", microtime(true) - $startTime, "s\n"; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$value = $obj->getPrivateProp(); | |
} | |
echo "Get private property via getter: ", microtime(true) - $startTime, "s\n"; | |
$startTime = microtime(true); | |
for ($i = 0; $i < $n; $i++) { | |
$value = $obj->privateProp; | |
} | |
echo "Get private property via magic: ", microtime(true) - $startTime, "s\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Frameworks...